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

      exports({
        BitMask: BitMask,
        CCClass: CCClass,
        Enum: Enum,
        Eventify: Eventify,
        WorldNode3DToLocalNodeUI: WorldNode3DToLocalNodeUI,
        WorldNode3DToWorldNodeUI: WorldNode3DToWorldNodeUI,
        __checkObsoleteInNamespace__: __checkObsoleteInNamespace__,
        __checkObsolete__: __checkObsolete__,
        _resetDebugSetting: _resetDebugSetting,
        absMax: absMax,
        absMaxComponent: absMaxComponent,
        applyMixins: applyMixins,
        approx: approx,
        assert: assert,
        assertID: assertID,
        assertIsNonNullable: assertIsNonNullable,
        assertIsTrue: assertIsTrue,
        assertsArrayIndex: assertsArrayIndex,
        bezier: bezier$1,
        bezierByTime: bezierByTime,
        binarySearch: binarySearch,
        binarySearchBy: binarySearchBy,
        binarySearchEpsilon: binarySearchEpsilon,
        ccenum: ccenum,
        clamp: clamp$1,
        clamp01: clamp01,
        color: color,
        computeRatioByType: computeRatioByType,
        createDefaultPipeline: createDefaultPipeline,
        debug: debug,
        debugID: debugID,
        deprecateModuleExportedName: deprecateModuleExportedName,
        deserialize: deserialize,
        enumerableProps: enumerableProps,
        equals: equals$2,
        error: error,
        errorID: errorID,
        find: find,
        flattenCodeArray: flattenCodeArray,
        floatToHalf: floatToHalf,
        formerlySerializedAs: formerlySerializedAs$2,
        fragmentText: fragmentText,
        getBaselineOffset: getBaselineOffset,
        getEnglishWordPartAtFirst: getEnglishWordPartAtFirst,
        getEnglishWordPartAtLast: getEnglishWordPartAtLast,
        getError: getError,
        getPathFromRoot: getPathFromRoot,
        getSerializationMetadata: getSerializationMetadata,
        getSymbolAt: getSymbolAt,
        getSymbolCodeAt: getSymbolCodeAt,
        getSymbolLength: getSymbolLength,
        getWorldTransformUntilRoot: getWorldTransformUntilRoot,
        halfToFloat: halfToFloat,
        instantiate: instantiate,
        inverseLerp: inverseLerp,
        isCCClassOrFastDefined: isCCClassOrFastDefined,
        isCCObject: isCCObject,
        isDisplayStats: isDisplayStats,
        isEnglishWordPartAtFirst: isEnglishWordPartAtFirst,
        isEnglishWordPartAtLast: isEnglishWordPartAtLast,
        isUnicodeCJK: isUnicodeCJK,
        isUnicodeSpace: isUnicodeSpace,
        isValid: isValid,
        lerp: lerp,
        loadWasmModuleSpine: loadWasmModuleSpine,
        log: log,
        logID: logID,
        mat4: mat4,
        murmurhash2_32_gc: murmurhash2_32_gc,
        nextPow2: nextPow2,
        pingPong: pingPong,
        pseudoRandom: pseudoRandom,
        pseudoRandomRange: pseudoRandomRange,
        pseudoRandomRangeInt: pseudoRandomRangeInt,
        quat: quat,
        random: random,
        randomRange: randomRange,
        randomRangeInt: randomRangeInt,
        rect: rect,
        repeat: repeat$2,
        safeMeasureText: safeMeasureText,
        sampleAnimationCurve: sampleAnimationCurve,
        setDefaultLogTimes: setDefaultLogTimes,
        setDisplayStats: setDisplayStats,
        setPropertyEnumType: setPropertyEnumType,
        setPropertyEnumTypeOnAttrs: setPropertyEnumTypeOnAttrs,
        setRandGenerator: setRandGenerator,
        shift: shift,
        size: size,
        toDegree: toDegree,
        toRadian: toRadian,
        tween: tween,
        tweenUtil: tweenUtil,
        v2: v2$1,
        v3: v3,
        v4: v4,
        warn: warn,
        warnID: warnID
      });

      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 OPEN_HARMONY = false;
      tryDefineGlobal('CC_WECHAT', 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);
      tryDefineGlobal('CC_MIGU', 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);
      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 = true;
      tryDefineGlobal('CC_JSB', true);

      const _global = typeof window === 'undefined' ? global : window;
      const cclegacy = exports("cclegacy", {
        _global
      });
      const legacyCC = cclegacy;
      cclegacy.internal = {};
      const engineVersion = exports("VERSION", '3.8.5');
      _global.CocosEngine = legacyCC.ENGINE_VERSION = engineVersion;
      _global.cc = legacyCC;
      const ccwindow$1 = typeof globalThis.jsb !== 'undefined' ? typeof jsb.window !== 'undefined' ? jsb.window : globalThis : globalThis;
      _global.ccwindow = ccwindow$1;

      const INT_BITS = 32;
      const INT_MAX = 0x7fffffff;
      const INT_MIN = -1 << INT_BITS - 1;
      function sign$2(v) {
        return (v > 0) - (v < 0);
      }
      function abs$7(v) {
        const mask = v >> INT_BITS - 1;
        return (v ^ mask) - mask;
      }
      function min$8(x, y) {
        return y ^ (x ^ y) & -(x < y);
      }
      function max$b(x, y) {
        return x ^ (x ^ y) & -(x < y);
      }
      function isPow2(v) {
        return !(v & v - 1) && !!v;
      }
      function log2(v) {
        let r;
        let 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) {
        let 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;
      }
      const REVERSE_TABLE = new Array(256);
      (tab => {
        for (let i = 0; i < 256; ++i) {
          let v = i;
          let r = i;
          let 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) {
        const 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,
        abs: abs$7,
        countTrailingZeros: countTrailingZeros,
        deinterleave2: deinterleave2,
        deinterleave3: deinterleave3,
        interleave2: interleave2,
        interleave3: interleave3,
        isPow2: isPow2,
        log10: log10,
        log2: log2,
        max: max$b,
        min: min$8,
        nextCombination: nextCombination,
        nextPow2: nextPow2$1,
        parity: parity,
        popCount: popCount,
        prevPow2: prevPow2,
        reverse: reverse,
        sign: sign$2
      });
      exports("bits", 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.",
      	"1222": "Failed to initialize render pipeline.",
      	"1223": "Custom pipeline and legacy pipeline are all culled.",
      	"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",
      	"1640": "Node %s(%s) has not attached to a scene.",
      	"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.",
      	"2301": "Cannot create the same touch object.",
      	"2302": "The touches is more than MAX_TOUCHES, release touch id %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 specify \"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 specify 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 specify \"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",
      	"9642": "[Physics] PhysicsSystem initDefaultMaterial() Failed to load builtinMaterial.",
      	"9643": "[Physics] Failed to load user customized default physics material: %s, will fallback to built-in default physics material",
      	"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 reimport all effects (Menu->Developer->Refresh All Effect) and restart creator.",
      	"12104": "Create shader %s failed.",
      	"12105": "Pass resources incomplete.",
      	"12106": "Cannot patch non-builtin macros.",
      	"12107": "Custom pipeline invalid render pass, program: %s. Please reimport all effects (Menu->Developer->Refresh All Effect) and restart creator.",
      	"12108": "Custom pipeline invalid render phase, program: %s. Please reimport all effects (Menu->Developer->Refresh All Effect) and restart creator.",
      	"12109": "custom-pipeline module not available.",
      	"12110": "MaterialPass passID in legacy pipeline is wrongly initialized.",
      	"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.",
      	"16305": "failed to stop accelerometer",
      	"16306": "The data must have positions field",
      	"16307": "please change type to sprite_stencil first",
      	"16308": "illegal index count!",
      	"16309": "Unsupported Format, convert to WebGL internal format failed.",
      	"16310": "Unsupported Format, convert to WebGL format failed.",
      	"16311": "Unsupported GLType, convert to GL type failed.",
      	"16312": "Unsupported GLType, convert to TypedArrayConstructor failed.",
      	"16313": "Unsupported GLType, convert to Type failed.",
      	"16314": "Unsupported GLType, get type failed.",
      	"16315": "Unsupported BufferType, create buffer failed.",
      	"16316": "Unsupported BufferType, update buffer failed.",
      	"16317": "Unsupported TextureType, create texture failed.",
      	"16318": "glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
      	"16319": "glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",
      	"16320": "glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS",
      	"16321": "glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED",
      	"16322": "Unsupported ShaderType.",
      	"16323": "%s in '%s' compilation failed.",
      	"16324": "Shader source dump: %s",
      	"16325": "Shader '%s' compilation succeeded.",
      	"16326": "Failed to link shader: %s",
      	"16327": "Unsupported GL texture type, copy buffer to texture failed.",
      	"16328": "Command 'draw' must be recorded inside a render pass.",
      	"16329": "Command 'updateBuffer' must be recorded outside a render pass.",
      	"16330": "Command 'copyBufferToTexture' must be recorded outside a render pass.",
      	"16331": "InputAssemblerInfo.vertexBuffers is null.",
      	"16332": "Illegal index buffer stride.",
      	"16333": "This device does not support WebGL.",
      	"16334": "A Class already exists with the same %s : %s. %s",
      	"16335": "\"%s\" has already been set as name or alias of another class.",
      	"16336": "\"%s\" has already been set as id or alias of another class.",
      	"16337": "can not support canvas rendering in 3D",
      	"16338": "The '_$erialized' prop in MissingScript is missing. Please contact jare.",
      	"16339": "Error props: ['%s']",
      	"16340": "Error when checking MissingScript 5, %s",
      	"16341": "The '_$erialized' prop of MissingScript is missing. Will force the raw data to be save.",
      	"16342": "Error props: ['%s']. Please contact jare.",
      	"16343": "Unable to stash previously serialized data. %s",
      	"16344": "Error when checking MissingScript 6, %s",
      	"16345": "uniform '%s' must have a count",
      	"16346": "Invalid GFX API!",
      	"16347": "The number of mipmaps of each face is different.",
      	"16348": "builtin UBO '%s' not available!",
      	"16349": "builtin samplerTexture '%s' not available!",
      	"16350": "The asset %s is missing!",
      	"16351": "the native asset of %s is missing!",
      	"16352": "The asset %s is invalid for some reason, detail message: %s, stack: %s",
      	"16353": "Can't find letter in this bitmap-font",
      	"16354": "Can't find letter definition in texture atlas %s for letter:%s",
      	"16355": "Can't find letter definition in font family %s for letter: %s",
      	"16356": "wrong format of version when compare version",
      	"16357": "should use Vec3.multiply for vector * vector operation",
      	"16358": "should use Vec3.scale for vector * scalar operation",
      	"16359": "should use Vec2.multiply for vector * vector operation",
      	"16360": "should use Vec2.scale for vector * scalar operation",
      	"16361": "should use Vec4.multiply for vector * vector operation",
      	"16362": "should use Vec4.scale for vector * scalar operation",
      	"16363": "Unable to get device",
      	"16364": "bitNum can't be undefined",
      	"16365": "maximum layers reached.",
      	"16366": "do not change buildin layers.",
      	"16367": "name can't be undefined",
      	"16368": "Unable to access unknown layer.",
      	"16369": "unknown define type '%s'",
      	"16370": "Shaders in material asset '%s' cannot be modified at runtime, please instantiate the material first.",
      	"16371": "Pipeline states in material asset '%s' cannot be modified at runtime, please instantiate the material first.",
      	"16372": "illegal pass index: %s.",
      	"16373": "illegal property name: %s.",
      	"16374": "Unexpected attribute!",
      	"16375": "Unexpected: failed to create morph texture?",
      	"16376": "The fnt config is not exists!",
      	"16377": "SpriteAtlas is null.",
      	"16378": "node '%s' doesn't have any renderable component",
      	"16379": "cannot resize buffer views!",
      	"16380": "cannot update through buffer views!",
      	"16381": "Profiler._stats is deprecated, please use Profiler.stats instead.",
      	"16382": "reverse: could not reverse a non-relative action",
      	"16383": "Need 'clone' for custom prop '%s'",
      	"16384": "Need 'add' for custom prop '%s'",
      	"16385": "Need 'sub' for custom prop '%s' in reverse mode",
      	"16386": "TweenAction: '%s' can't be converted to number",
      	"16387": "Wrong return type for 'progress', number or string needed",
      	"16388": "reverse: current tween could not be reversed, empty actions",
      	"16389": "pause: tween wasn't started, can't pause",
      	"16390": "resume: tween wasn't started, can't resume",
      	"16391": "reverse: could not find action id %s",
      	"16392": "Please set target to tween first",
      	"16393": "start: no actions in Tween",
      	"16394": "repeatForever: the last action is not ActionInterval",
      	"16395": "reverseTime: the last action is not ActionInterval",
      	"16396": "tweenUtil' is deprecated, please use 'tween' instead",
      	"16397": "ProgressBar FILLED mode only works when barSprite's Type is FILLED!",
      	"16398": "ProgressBar non-FILLED mode only works when barSprite's Type is non-FILLED!",
      	"16399": "CopyTextureToBuffers: not supported texture target.",
      	"16400": "Limit values to be greater than 0",
      	"16401": "beginRenderPass: Only primary command buffer is supported.",
      	"16402": "execute is not supported.",
      	"16403": "GPU memory alias is not supported",
      	"16404": "Block '%s' does not bound",
      	"16405": "This device does not support WebGL2",
      	"16406": "Can't find the spriteFrame of tilesets %s",
      	"16407": "Spline error: invalid mode",
      	"0100": "%s not yet implemented.",
      	"0200": "You should specify a valid DOM canvas element."
      };

      const ccdocument$6 = ccwindow$1.document;
      let logList = null;
      let ccLog = console.log.bind(console);
      let ccWarn = ccLog;
      let ccError = ccLog;
      let ccAssert = (condition, message, ...optionalParams) => {
        if (!condition) {
          console.log(`ASSERT: ${formatString(message, ...optionalParams)}`);
        }
      };
      let ccDebug = ccLog;
      function formatString(...data) {
        return legacyCC.js.formatStr.apply(null, data);
      }
      function log(...data) {
        return ccLog(...data);
      }
      function warn(...data) {
        return ccWarn(...data);
      }
      function error(...data) {
        return ccError(...data);
      }
      function assert(condition, message, ...optionalParams) {
        return ccAssert(condition, message, ...optionalParams);
      }
      function debug(...data) {
        return ccDebug(...data);
      }
      function _resetDebugSetting(mode) {
        ccLog = ccWarn = ccError = ccAssert = ccDebug = () => {};
        if (mode === 0) {
          return;
        }
        if (mode > 4) {
          const logToWebPage = msg => {
            if (!legacyCC.game.canvas) {
              return;
            }
            if (!logList) {
              const logDiv = ccdocument$6.createElement('Div');
              logDiv.setAttribute('id', 'logInfoDiv');
              logDiv.setAttribute('width', '200');
              const height = legacyCC.game.canvas.height;
              logDiv.setAttribute('height', `${height}`);
              const logDivStyle = logDiv.style;
              logDivStyle.zIndex = '99999';
              logDivStyle.position = 'absolute';
              logDivStyle.top = logDivStyle.left = '0';
              logList = ccdocument$6.createElement('textarea');
              logList.setAttribute('rows', '20');
              logList.setAttribute('cols', '30');
              logList.setAttribute('disabled', 'true');
              const 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 = (...data) => {
            logToWebPage(`ERROR :  ${formatString(...data)}`);
          };
          ccAssert = (condition, message, ...optionalParams) => {
            if (!condition) {
              logToWebPage(`ASSERT: ${formatString(message, ...optionalParams)}`);
            }
          };
          if (mode !== 7) {
            ccWarn = (...data) => {
              logToWebPage(`WARN :  ${formatString(...data)}`);
            };
          }
          if (mode === 5) {
            ccLog = (...data) => {
              logToWebPage(formatString(...data));
            };
          }
        } 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 = console.error ;
          }
          ccAssert = (condition, message, ...optionalParams) => {
            if (!condition) {
              const errorText = formatString(message, ...optionalParams);
              {
                throw new Error(errorText);
              }
            }
          };
        }
        if (mode !== 4) {
          if (console.warn.bind) {
            ccWarn = console.warn.bind(console);
          } else {
            ccWarn = console.warn ;
          }
        }
        if (mode <= 2) {
          {
            ccLog = console.log;
          }
        }
        if (mode <= 1) {
          if (typeof console.debug === 'function') {
            const vendorDebug = console.debug.bind(console);
            ccDebug = (...data) => vendorDebug(...data);
          }
        }
      }
      function _throw(error_) {
        {
          const stack = error_.stack;
          if (stack) {
            error(`${error_}\n${stack}` );
          } else {
            error(error_);
          }
          return undefined;
        }
      }
      function getTypedFormatter(type) {
        return (id, ...args) => {
          const msg = debugInfos[id] || 'unknown id' ;
          if (args.length === 0) {
            return msg;
          }
          return formatString(msg, ...args) ;
        };
      }
      const logFormatter = getTypedFormatter();
      function logID(id, ...optionalParams) {
        log(logFormatter(id, ...optionalParams));
      }
      const debugFormatter = getTypedFormatter();
      function debugID(id, ...optionalParams) {
        debug(debugFormatter(id, ...optionalParams));
      }
      const warnFormatter = getTypedFormatter();
      function warnID(id, ...optionalParams) {
        warn(warnFormatter(id, ...optionalParams));
      }
      const errorFormatter = getTypedFormatter();
      function errorID(id, ...optionalParams) {
        error(errorFormatter(id, ...optionalParams));
      }
      const assertFormatter = getTypedFormatter();
      function assertID(condition, id, ...optionalParams) {
        if (condition) {
          return;
        }
        assert(false, assertFormatter(id, ...optionalParams));
      }
      const DebugMode = exports("DebugMode", {
        "NONE": 0,
        "VERBOSE": 1,
        "INFO": 2,
        "WARN": 3,
        "ERROR": 4,
        "INFO_FOR_WEB_PAGE": 5,
        "WARN_FOR_WEB_PAGE": 6,
        "ERROR_FOR_WEB_PAGE": 7
      });
      function getError(errorId, ...param) {
        return errorFormatter(errorId, ...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,
        DebugMode: DebugMode,
        _resetDebugSetting: _resetDebugSetting,
        _throw: _throw,
        assert: assert,
        assertID: assertID,
        debug: debug,
        debugID: debugID,
        error: error,
        errorID: errorID,
        getError: getError,
        isDisplayStats: isDisplayStats,
        log: log,
        logID: logID,
        setDisplayStats: setDisplayStats,
        warn: warn,
        warnID: warnID
      });

      let defaultLogTimes = 10;
      function setDefaultLogTimes(times) {
        if (times > 0) {
          defaultLogTimes = times;
        }
      }
      let replaceProperty; exports("replaceProperty", replaceProperty);
      let removeProperty; exports("removeProperty", removeProperty);
      let markAsWarning; exports("markAsWarning", markAsWarning);
      let replacePropertyLog;
      let markAsWarningLog;
      let removePropertyLog;
      let messageID = 0;
      const messageMap = new Map();
      replacePropertyLog = (n, dp, n2, newp, f, id, s) => {
        const 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("replaceProperty", replaceProperty = (owner, ownerName, properties) => {
        if (owner == null) return;
        properties.forEach(item => {
          const id = messageID++;
          messageMap.set(id, {
            id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          const target = item.target != null ? item.target : owner;
          const newName = item.newName != null ? item.newName : item.name;
          const targetName = item.targetName != null ? item.targetName : ownerName;
          const sameTarget = target === owner;
          const suggest = item.suggest ? `(${item.suggest})` : '';
          if (item.customFunction != null) {
            owner[item.name] = function () {
              replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
              return item.customFunction.call(this, ...arguments);
            };
          } else if (item.customSetter != null || item.customGetter != null) {
            const hasSetter = item.customSetter != null;
            const hasGetter = item.customGetter != null;
            if (hasSetter && hasGetter) {
              Object.defineProperty(owner, item.name, {
                get() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                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(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() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                enumerable: false
              });
            }
          } else {
            Object.defineProperty(owner, item.name, {
              get() {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                return sameTarget ? this[newName] : target[newName];
              },
              set(v) {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                if (sameTarget) {
                  this[newName] = v;
                } else {
                  target[newName] = v;
                }
              },
              enumerable: false
            });
          }
        });
      });
      removePropertyLog = (n, dp, f, id, s) => {
        const item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f(`'%s' has been removed. ${s}`, `${n}.${dp}`);
          item.count++;
        }
      };
      exports("removeProperty", removeProperty = (owner, ownerName, properties) => {
        if (owner == null) return;
        properties.forEach(item => {
          const id = messageID++;
          messageMap.set(id, {
            id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          const suggest = item.suggest ? `(${item.suggest})` : '';
          Object.defineProperty(owner, item.name, {
            get() {
              return removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            set() {
              removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            enumerable: false
          });
        });
      });
      markAsWarningLog = (n, dp, f, id, s) => {
        const item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f(`'%s' is deprecated. ${s}`, `${n}.${dp}`);
          item.count++;
        }
      };
      exports("markAsWarning", markAsWarning = (owner, ownerName, properties) => {
        if (owner == null) return;
        const _defaultGetSet = (d, n, dp, f, id, s) => {
          if (d.get) {
            const oldGet = d.get;
            d.get = function () {
              markAsWarningLog(n, dp, f, id, s);
              return oldGet.call(this);
            };
          }
          if (d.set) {
            const oldSet = d.set;
            d.set = function (v) {
              markAsWarningLog(n, dp, f, id, s);
              oldSet.call(this, v);
            };
          }
          Object.defineProperty(owner, dp, d);
        };
        properties.forEach(item => {
          const deprecatedProp = item.name;
          const descriptor = Object.getOwnPropertyDescriptor(owner, deprecatedProp);
          if (!descriptor || !descriptor.configurable) {
            return;
          }
          const id = messageID++;
          messageMap.set(id, {
            id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          const suggest = item.suggest ? `(${item.suggest})` : '';
          if (typeof descriptor.value !== 'undefined') {
            if (typeof descriptor.value === 'function') {
              const oldValue = descriptor.value;
              owner[deprecatedProp] = function () {
                markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                return oldValue.call(this, ...arguments);
              };
            } else {
              let oldValue = descriptor.value;
              Object.defineProperty(owner, deprecatedProp, {
                configurable: true,
                get() {
                  markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                  return oldValue;
                }
              });
              if (descriptor.writable) {
                Object.defineProperty(owner, deprecatedProp, {
                  set(value) {
                    markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                    oldValue = value;
                  }
                });
              }
            }
          } else {
            _defaultGetSet(descriptor, ownerName, deprecatedProp, warn, id, suggest);
          }
          Object.defineProperty(owner, deprecatedProp, {
            enumerable: false
          });
        });
      });
      const topLevelDeprecateList = {};
      function deprecateModuleExportedName(deprecateList) {
        for (let deprecateName in deprecateList) {
          const deprecateInfo = deprecateList[deprecateName];
          topLevelDeprecateList[deprecateName] = deprecateInfo;
        }
      }
      function _checkObsoleteByName(checkName) {
        const deprecateInfo = topLevelDeprecateList[checkName];
        if (!deprecateInfo) {
          return;
        }
        const {
          newName,
          since,
          removed
        } = deprecateInfo;
        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 (let checkName of checkList) {
          _checkObsoleteByName(checkName);
        }
      }
      let _cachedProxy;
      function __checkObsoleteInNamespace__(ccNamespace) {
        if (!_cachedProxy) {
          if (typeof Proxy === 'undefined') {
            _cachedProxy = {};
          } else {
            _cachedProxy = new Proxy(ccNamespace, {
              get(target, name, receiver) {
                _checkObsoleteByName(name);
                return Reflect.get(target, name, receiver);
              }
            });
          }
        }
        return _cachedProxy;
      }

      var _class$2z;
      const NonUuidMark = '.';
      class IDGenerator {
        constructor(category) {
          this.id = 0 | Math.random() * 998;
          this.prefix = category ? category + NonUuidMark : '';
        }
        getNewId() {
          return this.prefix + (++this.id).toString();
        }
      }
      _class$2z = IDGenerator;
      IDGenerator.global = new _class$2z('global');

      const tempCIDGenerator = new IDGenerator('TmpCId.');
      const aliasesTag = typeof Symbol === 'undefined' ? '__aliases__' : Symbol('[[Aliases]]');
      const classNameTag = '__classname__';
      const 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 (const key in obj) {
          return false;
        }
        return true;
      }
      const value = (() => {
        const descriptor = {
          value: undefined,
          enumerable: false,
          writable: false,
          configurable: true
        };
        return (object, propertyName, value_, writable, enumerable) => {
          descriptor.value = value_;
          descriptor.writable = writable;
          descriptor.enumerable = enumerable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.value = undefined;
        };
      })();
      const getset = (() => {
        const descriptor = {
          get: undefined,
          set: undefined,
          enumerable: false
        };
        return (object, propertyName, getter, setter, enumerable = false, 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;
        };
      })();
      const get = (() => {
        const descriptor = {
          get: undefined,
          enumerable: false,
          configurable: false
        };
        return (object, propertyName, getter, enumerable, configurable) => {
          descriptor.get = getter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.get = undefined;
        };
      })();
      const set = (() => {
        const descriptor = {
          set: undefined,
          enumerable: false,
          configurable: false
        };
        return (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) {
        const map = Object.create(null);
        if (forceDictMode) {
          const INVALID_IDENTIFIER_1 = '.';
          const 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') {
          const prototype = objOrCtor.prototype;
          if (prototype && prototype.hasOwnProperty(classNameTag) && prototype[classNameTag]) {
            return prototype[classNameTag];
          }
          let ret = '';
          if (objOrCtor.name) {
            ret = objOrCtor.name;
          } else if (objOrCtor.toString) {
            let arr;
            const 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) {
        const extractPropName = /([^.]+)$/;
        const oldProp = extractPropName.exec(obsoleted)[0];
        const 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 (const obsoleted in props) {
          const newName = props[obsoleted];
          obsolete(obj, `${objName}.${obsoleted}`, newName, writable);
        }
      }
      const REGEXP_NUM_OR_STR = /(%d)|(%s)/;
      const REGEXP_STR = /%s/;
      function formatStr(msg, ...subst) {
        if (arguments.length === 0) {
          return '';
        }
        if (subst.length === 0) {
          return `${msg}`;
        }
        const hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg);
        if (hasSubstitution) {
          for (const arg of subst) {
            const regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;
            if (regExpToTest.test(msg)) {
              const notReplaceFunction = `${arg}`;
              msg = msg.replace(regExpToTest, notReplaceFunction);
            } else {
              msg += ` ${arg}`;
            }
          }
        } else {
          for (const arg of subst) {
            msg += ` ${arg}`;
          }
        }
        return msg;
      }
      function shiftArguments() {
        const len = arguments.length - 1;
        const args = new Array(len);
        for (let i = 0; i < len; ++i) {
          args[i] = arguments[i + 1];
        }
        return args;
      }
      function getPropertyDescriptor(object, propertyName) {
        while (object) {
          const pd = Object.getOwnPropertyDescriptor(object, propertyName);
          if (pd) {
            return pd;
          }
          object = Object.getPrototypeOf(object);
        }
        return null;
      }
      function _copyProp(name, source, target) {
        const pd = getPropertyDescriptor(source, name);
        if (pd) {
          Object.defineProperty(target, name, pd);
        }
      }
      function copyAllProperties(source, target, excepts) {
        const propertyNames = Object.getOwnPropertyNames(source);
        for (let i = 0, len = propertyNames.length; i < len; ++i) {
          const propertyName = propertyNames[i];
          if (excepts.indexOf(propertyName) !== -1) {
            continue;
          }
          _copyProp(propertyName, source, target);
        }
      }
      function addon(object, ...sources) {
        object = object || {};
        for (const source of sources) {
          if (source) {
            if (typeof source !== 'object') {
              errorID(5402, source);
              continue;
            }
            for (const name in source) {
              if (!(name in object)) {
                _copyProp(name, source, object);
              }
            }
          }
        }
        return object;
      }
      function mixin(object, ...sources) {
        object = object || {};
        for (const source of sources) {
          if (source) {
            if (typeof source !== 'object') {
              errorID(5403, source);
              continue;
            }
            for (const name in source) {
              _copyProp(name, source, object);
            }
          }
        }
        return object;
      }
      function extend(cls, base) {
        for (const 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) {
        const proto = constructor.prototype;
        const 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 (const key of Object.keys(object)) {
          delete object[key];
        }
      }
      function isTempClassId(id) {
        return typeof id !== 'string' || id.startsWith(tempCIDGenerator.prefix);
      }
      const _idToClass = createMap(true);
      const _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) {
            const registered = table[id];
            if (!allowExist && registered && registered !== constructor) {
              let detail = '';
              errorID(16334, tag, id, detail);
            } else {
              table[id] = constructor;
            }
          }
        };
      }
      const _setClassId = setup('__cid__', _idToClass, false);
      const doSetClassName = setup('__classname__', _nameToClass, true);
      function setClassName(className, constructor) {
        doSetClassName(className, constructor);
        if (!constructor.prototype.hasOwnProperty(classIdTag)) {
          const id = className || tempCIDGenerator.getNewId();
          if (id) {
            _setClassId(id, constructor);
          }
        }
      }
      function setClassAlias(target, alias) {
        const nameRegistry = _nameToClass[alias];
        const idRegistry = _idToClass[alias];
        let ok = true;
        if (nameRegistry && nameRegistry !== target) {
          errorID(16335, alias);
          ok = false;
        }
        if (idRegistry && idRegistry !== target) {
          errorID(16336, alias);
          ok = false;
        }
        if (ok) {
          let classAliases = target[aliasesTag];
          if (!classAliases) {
            classAliases = [];
            target[aliasesTag] = classAliases;
          }
          classAliases.push(alias);
          _nameToClass[alias] = target;
          _idToClass[alias] = target;
        }
      }
      function unregisterClass(...constructors) {
        for (const constructor of constructors) {
          const p = constructor.prototype;
          const classId = p[classIdTag];
          if (classId) {
            delete _idToClass[classId];
          }
          const classname = p[classNameTag];
          if (classname) {
            delete _nameToClass[classname];
          }
          const aliases = p[aliasesTag];
          if (aliases) {
            for (let iAlias = 0; iAlias < aliases.length; ++iAlias) {
              const 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;
        let 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) {
          const prototype = obj.constructor.prototype;
          if (prototype && prototype.hasOwnProperty(classIdTag)) {
            res = obj[classIdTag];
            if (!allowTempId && (EDITOR) && isTempClassId(res)) {
              return '';
            }
            return res;
          }
        }
        return '';
      }

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

      class MutableForwardIterator {
        constructor(array) {
          this.i = 0;
          this.array = array;
        }
        get length() {
          return this.array.length;
        }
        set length(value) {
          this.array.length = value;
          if (this.i >= value) {
            this.i = value - 1;
          }
        }
        remove(value) {
          const index = this.array.indexOf(value);
          if (index >= 0) {
            this.removeAt(index);
          }
        }
        removeAt(i) {
          this.array.splice(i, 1);
          if (i <= this.i) {
            --this.i;
          }
        }
        fastRemove(value) {
          const index = this.array.indexOf(value);
          if (index >= 0) {
            this.fastRemoveAt(index);
          }
        }
        fastRemoveAt(i) {
          const array = this.array;
          array[i] = array[array.length - 1];
          --array.length;
          if (i <= this.i) {
            --this.i;
          }
        }
        push(item) {
          this.array.push(item);
        }
      }
      function removeAt(array, index) {
        array.splice(index, 1);
      }
      function fastRemoveAt$2(array, index) {
        const length = array.length;
        if (index < 0 || index >= length) {
          return;
        }
        array[index] = array[length - 1];
        array.length = length - 1;
      }
      function remove(array, value) {
        const index = array.indexOf(value);
        if (index >= 0) {
          removeAt(array, index);
          return true;
        } else {
          return false;
        }
      }
      function fastRemove(array, value) {
        const index = array.indexOf(value);
        if (index >= 0) {
          array[index] = array[array.length - 1];
          --array.length;
        }
      }
      function removeIf(array, predicate) {
        const index = array.findIndex(predicate);
        if (index >= 0) {
          const value = array[index];
          removeAt(array, index);
          return value;
        }
        return undefined;
      }
      function verifyType(array, type) {
        if (array && array.length > 0) {
          for (const item of array) {
            if (!(item instanceof type)) {
              logID(1300);
              return false;
            }
          }
        }
        return true;
      }
      function removeArray(array, removals) {
        for (let i = 0, l = removals.length; i < l; i++) {
          remove(array, removals[i]);
        }
      }
      function appendObjectsAt(array, objects, index) {
        array.splice.apply(array, [index, 0, ...objects]);
        return array;
      }
      function contains$2(array, value) {
        return array.indexOf(value) >= 0;
      }
      function copy(array) {
        const len = array.length;
        const cloned = new Array(len);
        for (let i = 0; i < len; i += 1) {
          cloned[i] = array[i];
        }
        return cloned;
      }

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

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

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

      function BitMask(obj) {
        if ('__bitmask__' in obj) {
          return obj;
        }
        value(obj, '__bitmask__', null, true);
        let lastIndex = -1;
        const keys = Object.keys(obj);
        for (let i = 0; i < keys.length; i++) {
          const key = keys[i];
          let 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;
          }
          const reverseKey = `${val}`;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        return obj;
      }
      BitMask.isBitMask = BitMaskType => BitMaskType && Object.prototype.hasOwnProperty.call(BitMaskType, '__bitmask__');
      BitMask.getList = BitMaskDef => {
        if (BitMaskDef.__bitmask__) {
          return BitMaskDef.__bitmask__;
        }
        return BitMask.update(BitMaskDef);
      };
      BitMask.update = BitMaskDef => {
        if (!Array.isArray(BitMaskDef.__bitmask__)) {
          BitMaskDef.__bitmask__ = [];
        }
        const bitList = BitMaskDef.__bitmask__;
        bitList.length = 0;
        for (const name in BitMaskDef) {
          const v = BitMaskDef[name];
          if (Number.isInteger(v)) {
            bitList.push({
              name,
              value: v
            });
          }
        }
        bitList.sort((a, b) => 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})`);
      }

      const hasOwnPropertyProto = Object.prototype.hasOwnProperty;
      function Enum(obj) {
        if ('__enums__' in obj) {
          return obj;
        }
        value(obj, '__enums__', null, true);
        return Enum.update(obj);
      }
      Enum.update = obj => {
        let lastIndex = -1;
        const keys = Object.keys(obj);
        for (let i = 0; i < keys.length; i++) {
          const key = keys[i];
          let 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;
          }
          const reverseKey = `${val}`;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        if (Array.isArray(obj.__enums__)) {
          updateList(obj);
        }
        return obj;
      };
      (function (_Enum) {})(Enum || (exports("Enum", Enum = {})));
      Enum.isEnum = enumType => enumType && hasOwnPropertyProto.call(enumType, '__enums__');
      function assertIsEnum(enumType) {
        assertIsTrue(hasOwnPropertyProto.call(enumType, '__enums__'));
      }
      Enum.getList = enumType => {
        assertIsEnum(enumType);
        if (enumType.__enums__) {
          return enumType.__enums__;
        }
        return updateList(enumType);
      };
      function updateList(enumType) {
        assertIsEnum(enumType);
        const enums = enumType.__enums__ || [];
        enums.length = 0;
        let isAllInteger = true;
        for (const name in enumType) {
          const v = enumType[name];
          const isIntegerValue = Number.isInteger(v);
          if (!isIntegerValue) {
            isAllInteger = false;
          }
          if (isIntegerValue || typeof v === 'string' && enumType[v] !== Number.parseInt(name)) {
            enums.push({
              name,
              value: v
            });
          }
        }
        if (isAllInteger) {
          enums.sort((a, b) => a.value - b.value);
        }
        enumType.__enums__ = enums;
        return enums;
      }
      Enum.sortList = (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;

      class ValueType {
        clone() {
          errorID(100, `${getClassName(this)}.clone`);
          return this;
        }
        equals(other) {
          return false;
        }
        set(other) {
          errorID(100, `${getClassName(this)}.set`);
        }
        toString() {
          return `${''}`;
        }
      } exports("ValueType", ValueType);
      setClassName('cc.ValueType', ValueType);
      legacyCC.ValueType = ValueType;

      const SettingsCategory = exports("SettingsCategory", {
        "PATH": "path",
        "ENGINE": "engine",
        "ASSETS": "assets",
        "SCRIPTING": "scripting",
        "PHYSICS": "physics",
        "RENDERING": "rendering",
        "LAUNCH": "launch",
        "SCREEN": "screen",
        "SPLASH_SCREEN": "splashScreen",
        "ANIMATION": "animation",
        "PROFILING": "profiling",
        "PLUGINS": "plugins",
        "XR": "xr"
      });
      class Settings {
        constructor() {
          this._settings = {};
          this._override = {};
        }
        init(path = '', overrides = {}) {
          for (const categoryName in overrides) {
            const category = overrides[categoryName];
            if (category) {
              for (const name in category) {
                this.overrideSettings(categoryName, name, category[name]);
              }
            }
          }
          if (!path) return Promise.resolve();
          {
            if (window.oh && window.scriptEngineType === 'napi') {
              return new Promise((resolve, reject) => {
                const settingsModule = '../settings.js';
                module.import(settingsModule).then(res => {
                  this._settings = res.default;
                  resolve();
                }).catch(e => reject(e));
              });
            }
          }
          return new Promise((resolve, reject) => {
            if (!path.startsWith('http')) {
              {
                const result = fsUtils.readJsonSync(path);
                if (result instanceof Error) {
                  reject(result);
                } else {
                  this._settings = result;
                  resolve();
                }
              }
            } else {
              const xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'text';
              xhr.onload = () => {
                this._settings = JSON.parse(xhr.response);
                resolve();
              };
              xhr.onerror = () => {
                reject(new Error('request settings failed!'));
              };
              xhr.send(null);
            }
          });
        }
        overrideSettings(category, name, value) {
          if (!(category in this._override)) {
            this._override[category] = {};
          }
          this._override[category][name] = value;
        }
        querySettings(category, name) {
          if (category in this._override) {
            const categorySettings = this._override[category];
            if (categorySettings && name in categorySettings) {
              return categorySettings[name];
            }
          }
          if (category in this._settings) {
            const categorySettings = this._settings[category];
            if (categorySettings && name in categorySettings) {
              return categorySettings[name];
            }
          }
          return null;
        }
      } exports("Settings", Settings);
      Settings.Category = SettingsCategory;
      const settings = exports("settings", new Settings());
      legacyCC.settings = settings;

      let Orientation$1;
      (function (Orientation) {
        Orientation[Orientation["PORTRAIT"] = 1] = "PORTRAIT";
        Orientation[Orientation["PORTRAIT_UPSIDE_DOWN"] = 2] = "PORTRAIT_UPSIDE_DOWN";
        Orientation[Orientation["LANDSCAPE_LEFT"] = 4] = "LANDSCAPE_LEFT";
        Orientation[Orientation["LANDSCAPE_RIGHT"] = 8] = "LANDSCAPE_RIGHT";
        Orientation[Orientation["LANDSCAPE"] = 12] = "LANDSCAPE";
        Orientation[Orientation["AUTO"] = 13] = "AUTO";
      })(Orientation$1 || (Orientation$1 = {}));

      const SUPPORT_TEXTURE_FORMATS = ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png'];
      const 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
      };
      const macro = exports("macro", {
        SUPPORT_TEXTURE_FORMATS,
        KEY,
        RAD: Math.PI / 180,
        DEG: 180 / Math.PI,
        REPEAT_FOREVER: Number.MAX_VALUE - 1,
        FLT_EPSILON: 0.0000001192092896,
        ORIENTATION_PORTRAIT: Orientation$1.PORTRAIT,
        ORIENTATION_PORTRAIT_UPSIDE_DOWN: Orientation$1.PORTRAIT_UPSIDE_DOWN,
        ORIENTATION_LANDSCAPE: Orientation$1.LANDSCAPE,
        ORIENTATION_LANDSCAPE_LEFT: Orientation$1.LANDSCAPE_LEFT,
        ORIENTATION_LANDSCAPE_RIGHT: Orientation$1.LANDSCAPE_RIGHT,
        ORIENTATION_AUTO: Orientation$1.AUTO,
        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: 'Builtin',
        init() {
          {
            this.CLEANUP_IMAGE_CACHE = true;
          }
          const defaultValues = settings.querySettings("engine", 'macros');
          if (defaultValues) {
            for (const key in defaultValues) {
              macro[key] = defaultValues[key];
            }
          }
        }
      });
      legacyCC.macro = macro;

      function setTimeoutRAF(callback, delay, ...args) {
        var _globalThis$__globalX;
        const start = performance.now();
        const 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(callback, delay, ...args);
        }
        const handleRAF = () => {
          if (performance.now() - start < delay) {
            raf(handleRAF);
          } else {
            callback(...args);
          }
        };
        return raf(handleRAF);
      }

      const BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/;
      const BASE64_KEYS$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      const values = new Array(123);
      for (let i = 0; i < 123; ++i) {
        values[i] = 64;
      }
      for (let i = 0; i < 64; ++i) {
        values[BASE64_KEYS$1.charCodeAt(i)] = i;
      }
      const BASE64_VALUES$1 = values;
      function propertyDefine(ctor, sameNameGetSets, diffNameGetSets) {
        function define(np, propName, getter, setter) {
          const pd = Object.getOwnPropertyDescriptor(np, propName);
          if (pd) {
            if (pd.get && getter) {
              np[getter] = pd.get;
            }
            if (pd.set && setter) {
              np[setter] = pd.set;
            }
          } else {
            const getterFunc = np[getter];
            {
              getset(np, propName, getterFunc, np[setter]);
            }
          }
        }
        let propName;
        const np = ctor.prototype;
        for (let i = 0, len = sameNameGetSets.length; i < len; ++i) {
          propName = sameNameGetSets[i];
          const suffix = propName[0].toUpperCase() + propName.slice(1);
          define(np, propName, `get${suffix}`, `set${suffix}`);
        }
        for (propName in diffNameGetSets) {
          const gs = diffNameGetSets[propName];
          define(np, propName, gs[0], gs[1]);
        }
      }
      function pushToMap(map, key, value, pushFront) {
        const 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 {
          let 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, ...args) {
        if (callback) {
          setTimeoutRAF(() => {
            callback(...args);
          }, 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) {
          const 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,
        BASE64_VALUES: BASE64_VALUES$1,
        propertyDefine,
        pushToMap,
        contains: contains$1,
        isDomNode,
        callInNextTick,
        isPlainEmptyObj_DEV,
        clampf,
        degreesToRadians,
        radiansToDegrees
      };

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

      const DELIMETER$1 = '$_$';
      function createAttrsSingle(owner, superAttrs) {
        const attrs = superAttrs ? Object.create(superAttrs) : {};
        value(owner, '__attrs__', attrs);
        return attrs;
      }
      function createAttrs(subclass) {
        if (typeof subclass !== 'function') {
          const instance = subclass;
          return createAttrsSingle(instance, getClassAttrs(instance.constructor));
        }
        let superClass;
        const chains = legacyCC.Class.getInheritanceChain(subclass);
        for (let i = chains.length - 1; i >= 0; i--) {
          const cls = chains[i];
          const 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) {
        const attrs = getClassAttrs(constructor);
        const prefix = propertyName + DELIMETER$1;
        const ret = {};
        for (const 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;
      }
      class PrimitiveType {
        constructor(name, defaultValue) {
          this.name = name;
          this.default = defaultValue;
        }
        toString() {
          return this.name;
        }
      }
      const CCInteger = exports("CCInteger", new PrimitiveType('Integer', 0));
      legacyCC.Integer = CCInteger;
      legacyCC.CCInteger = CCInteger;
      const CCFloat = exports("CCFloat", new PrimitiveType('Float', 0.0));
      legacyCC.Float = CCFloat;
      legacyCC.CCFloat = CCFloat;
      const CCBoolean = exports("CCBoolean", new PrimitiveType('Boolean', false));
      legacyCC.Boolean = CCBoolean;
      legacyCC.CCBoolean = CCBoolean;
      const CCString = exports("CCString", new PrimitiveType('String', ''));
      legacyCC.String = CCString;
      legacyCC.CCString = CCString;
      function getTypeChecker_ET(type, attributeName) {
        return function (constructor, mainPropertyName) {
          const propInfo = `"${getClassName(constructor)}.${mainPropertyName}"`;
          const mainPropAttrs = attr(constructor, mainPropertyName);
          let 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;
          }
          const defaultVal = mainPropAttrs.default;
          if (typeof defaultVal === 'undefined') {
            return;
          }
          const isContainer = Array.isArray(defaultVal) || isPlainEmptyObj_DEV(defaultVal);
          if (isContainer) {
            return;
          }
          const defaultType = typeof defaultVal;
          const 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);
          const defaultDef = getClassAttrs(classCtor)[`${mainPropName + DELIMETER$1}default`];
          const defaultVal = legacyCC.Class.getDefault(defaultDef);
          if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, legacyCC.ValueType)) {
            const typename = getClassName(typeCtor);
            const 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,
        CCBoolean: CCBoolean,
        CCFloat: CCFloat,
        CCInteger: CCInteger,
        CCString: CCString,
        DELIMETER: DELIMETER$1,
        PrimitiveType: PrimitiveType,
        attr: attr,
        createAttrs: createAttrs,
        createAttrsSingle: createAttrsSingle,
        getClassAttrs: getClassAttrs,
        getObjTypeChecker_ET: getObjTypeChecker_ET,
        getTypeChecker_ET: getTypeChecker_ET,
        setClassAttr: setClassAttr
      });

      const SerializableAttrs = {
        default: {},
        serializable: {},
        editorOnly: {},
        formerlySerializedAs: {}
      };
      function parseNotify(val, propName, notify, properties) {
        if (val.get || val.set) {
          return;
        }
        if (val.hasOwnProperty('default')) {
          const newKey = `_N$${propName}`;
          val.get = function () {
            return this[newKey];
          };
          val.set = function (value) {
            const oldValue = this[newKey];
            this[newKey] = value;
            notify.call(this, oldValue);
          };
          const newValue = {};
          properties[newKey] = newValue;
          for (const attr in SerializableAttrs) {
            const 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) {
        const res = isGetset || typeof _default === 'undefined' ? {
          _short: true
        } : {
          _short: true,
          default: _default
        };
        if (type) {
          res.type = type;
        }
        return res;
      }
      function getFullFormOfProperty(options, isGetset) {
        const isLiteral = options && options.constructor === Object;
        if (!isLiteral) {
          if (Array.isArray(options) && options.length > 0) {
            return _wrapOptions(isGetset, [], options);
          } else if (typeof options === 'function') {
            const type = options;
            return _wrapOptions(isGetset, isChildClassOf(type, legacyCC.ValueType) ? new type() : null, type);
          } else if (options instanceof PrimitiveType) {
            return _wrapOptions(isGetset, undefined, options);
          } else {
            return _wrapOptions(isGetset, options);
          }
        }
        return null;
      }
      function preprocessAttrs(properties, className, cls) {
        for (const propName in properties) {
          let val = properties[propName];
          const fullForm = getFullFormOfProperty(val, false);
          if (fullForm) {
            val = properties[propName] = fullForm;
          }
          if (val) {
            const notify = val.notify;
            if (notify) {
              {
                parseNotify(val, propName, notify, properties);
              }
            }
            if ('type' in val) {
              parseType(val, val.type, className, propName);
            }
          }
        }
      }

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

      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);
      }

      const DELIMETER = DELIMETER$1;
      const CCCLASS_TAG = '__ctors__';
      const ENUM_TAG = exports("ENUM_TAG", 'Enum');
      const BITMASK_TAG = exports("BITMASK_TAG", '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) {
        const 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) {
        const 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) {
        const Component = legacyCC.Component;
        const frame = peek();
        if (frame && isChildClassOf(baseClass, Component)) {
          if (isChildClassOf(frame.cls, Component)) {
            errorID(3615);
            return null;
          }
          className = className || frame.script;
        }
        const cls = doDefine(className, baseClass, options);
        if (frame) {
          if (isChildClassOf(baseClass, Component)) {
            const 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) {
        const clsName = getClassName(value);
        const type = value.constructor;
        let res = `new ${clsName}(`;
        for (let i = 0; i < type.__props__.length; i++) {
          const prop = type.__props__[i];
          const 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');
      }
      const 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 (const propName in properties) {
            const val = properties[propName];
            if (!val.get && !val.set) {
              defineProp(cls, className, propName, val);
            } else {
              defineGetSet(cls, className, propName, val);
            }
          }
        }
        const attrs = getClassAttrs(cls);
        cls.__values__ = cls.__props__.filter(prop => attrs[`${prop}${DELIMETER}serializable`] !== false);
      }
      function CCClass(options) {
        let name = options.name;
        const base = options.extends;
        const cls = define$1(name, base, options);
        if (!name) {
          name = legacyCC.js.getClassName(cls);
        }
        cls._sealed = true;
        if (base) {
          base._sealed = false;
        }
        const properties = options.properties;
        declareProperties(cls, name, properties, base);
        const 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);
        const props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
        const attrs = getClassAttrs(constructor);
        for (let i = 0; i < props.length; i++) {
          const 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) {
        const chain = [];
        for (;;) {
          constructor = getSuper(constructor);
          if (!constructor) {
            break;
          }
          if (constructor !== Object) {
            chain.push(constructor);
          }
        }
        return chain;
      }
      CCClass.getInheritanceChain = getInheritanceChain;
      const PrimitiveTypes = {
        Integer: 'Number',
        Float: 'Number',
        Boolean: 'Boolean',
        String: 'String'
      };
      function parseAttributes(constructor, attributes, className, propertyName, usedInGetter) {
        let attrs = null;
        let propertyNamePrefix = '';
        function initAttrs() {
          propertyNamePrefix = propertyName + DELIMETER;
          return attrs = getClassAttrs(constructor);
        }
        if ('type' in attributes && typeof attributes.type === 'undefined') {
          warnID(3660, propertyName, className);
        }
        const type = attributes.type;
        if (type) {
          const 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;
        }
        const parseSimpleAttribute = (attributeName, expectType) => {
          if (attributeName in attributes) {
            const val = attributes[attributeName];
            if (typeof val === expectType) {
              (attrs || initAttrs())[propertyNamePrefix + attributeName] = val;
            }
          }
        };
        if (attributes.editorOnly) {
          {
            (attrs || initAttrs())[`${propertyNamePrefix}editorOnly`] = true;
          }
        }
        const isStandaloneMode = attributes.__internalFlags & 1;
        let normalizedSerializable;
        if (isStandaloneMode) {
          normalizedSerializable = attributes.serializable === true || (attributes.__internalFlags & 4) !== 0;
        } else if (attributes.serializable === false) {
          normalizedSerializable = false;
        }
        if (typeof normalizedSerializable !== 'undefined') {
          (attrs || initAttrs())[`${propertyNamePrefix}serializable`] = normalizedSerializable;
        }
        parseSimpleAttribute('formerlySerializedAs', 'string');
        const 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('step', 'number');
        parseSimpleAttribute('userData', 'object');
      }
      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;

      const _d2r = Math.PI / 180.0;
      const _r2d = 180.0 / Math.PI;
      let _random = Math.random;
      const HALF_PI = exports("HALF_PI", Math.PI * 0.5);
      const TWO_PI = exports("TWO_PI", Math.PI * 2.0);
      const EPSILON$2 = exports("EPSILON", 0.000001);
      function equals$2(a, b) {
        return Math.abs(a - b) <= EPSILON$2 * Math.max(1.0, Math.abs(a), Math.abs(b));
      }
      function approx(a, b, maxDiff) {
        maxDiff = maxDiff || EPSILON$2;
        return Math.abs(a - b) <= maxDiff;
      }
      function clamp$1(val, min, max) {
        if (min > max) {
          const 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(key => {
          Object.defineProperty(prototype, key, {
            enumerable: true
          });
        });
      }
      const toHalf = function toHalf() {
        const floatView = new Float32Array(1);
        const int32View = new Int32Array(floatView.buffer);
        return function toHalf(fval) {
          floatView[0] = fval;
          const fbits = int32View[0];
          const s = fbits >> 16 & 0x8000;
          const em = fbits & 0x7fffffff;
          let 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];
        };
      }();
      const fromHalf = function fromHalf() {
        const floatView = new Float32Array(1);
        const int32View = new Int32Array(floatView.buffer);
        return function fromHalf(hval) {
          const s = hval >> 15 & 0x00000001;
          const em = hval & 0x00007fff;
          let h = em << 13;
          let 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$2y;
      const abs$6 = Math.abs;
      const max$a = Math.max;
      const min$7 = Math.min;
      const PI$5 = Math.PI;
      const sin$6 = Math.sin;
      const cos$7 = Math.cos;
      const atan2$3 = Math.atan2;
      const sqrt$5 = Math.sqrt;
      const ceil$4 = Math.ceil;
      const floor$2 = Math.floor;
      const round$2 = Math.round;
      class Vec4 extends ValueType {
        static clone(a) {
          return new Vec4(a.x, a.y, a.z, a.w);
        }
        static copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        }
        static set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        }
        static fromColor(out, color) {
          out.x = color.r;
          out.y = color.g;
          out.z = color.b;
          out.w = color.a;
          return out;
        }
        static angle(a, b) {
          const dx = a.y * b.z - a.z * b.y;
          const dy = a.z * b.x - a.x * b.z;
          const dz = a.x * b.y - a.y * b.x;
          const dotVal = a.x * b.x + a.y * b.y + a.z * b.z;
          return atan2$3(sqrt$5(dx * dx + dy * dy + dz * dz), dotVal);
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static ceil(out, a) {
          out.x = ceil$4(a.x);
          out.y = ceil$4(a.y);
          out.z = ceil$4(a.z);
          out.w = ceil$4(a.w);
          return out;
        }
        static floor(out, a) {
          out.x = floor$2(a.x);
          out.y = floor$2(a.y);
          out.z = floor$2(a.z);
          out.w = floor$2(a.w);
          return out;
        }
        static min(out, a, b) {
          out.x = min$7(a.x, b.x);
          out.y = min$7(a.y, b.y);
          out.z = min$7(a.z, b.z);
          out.w = min$7(a.w, b.w);
          return out;
        }
        static max(out, a, b) {
          out.x = max$a(a.x, b.x);
          out.y = max$a(a.y, b.y);
          out.z = max$a(a.z, b.z);
          out.w = max$a(a.w, b.w);
          return out;
        }
        static round(out, a) {
          out.x = round$2(a.x);
          out.y = round$2(a.y);
          out.z = round$2(a.z);
          out.w = round$2(a.w);
          return out;
        }
        static 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;
        }
        static 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;
        }
        static distance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          const z = b.z - a.z;
          const w = b.w - a.w;
          return sqrt$5(x * x + y * y + z * z + w * w);
        }
        static squaredDistance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          const z = b.z - a.z;
          const w = b.w - a.w;
          return x * x + y * y + z * z + w * w;
        }
        static len(a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          const w = a.w;
          return sqrt$5(x * x + y * y + z * z + w * w);
        }
        static lengthSqr(a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          const w = a.w;
          return x * x + y * y + z * z + w * w;
        }
        static negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = -a.w;
          return out;
        }
        static 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;
        }
        static inverseSafe(out, a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          const w = a.w;
          if (abs$6(x) < EPSILON$2) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (abs$6(y) < EPSILON$2) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (abs$6(z) < EPSILON$2) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          if (abs$6(w) < EPSILON$2) {
            out.w = 0;
          } else {
            out.w = 1.0 / w;
          }
          return out;
        }
        static normalize(out, a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          const w = a.w;
          let len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / sqrt$5(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;
        }
        static dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        }
        static 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;
        }
        static 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;
        }
        static random(out, scale) {
          scale = scale || 1.0;
          const phi = random() * 2.0 * PI$5;
          const cosTheta = random() * 2 - 1;
          const sinTheta = sqrt$5(1 - cosTheta * cosTheta);
          out.x = sinTheta * cos$7(phi) * scale;
          out.y = sinTheta * sin$6(phi) * scale;
          out.z = cosTheta * scale;
          out.w = 0;
          return out;
        }
        static transformMat4(out, a, m) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          const 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;
        }
        static transformAffine(out, v, m) {
          const x = v.x;
          const y = v.y;
          const z = v.z;
          const 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;
        }
        static transformQuat(out, a, q) {
          const {
            x,
            y,
            z
          } = a;
          const _x = q.x;
          const _y = q.y;
          const _z = q.z;
          const _w = q.w;
          const ix = _w * x + _y * z - _z * y;
          const iy = _w * y + _z * x - _x * z;
          const iz = _w * z + _x * y - _y * x;
          const 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;
        }
        static toArray(out, v, ofs = 0) {
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          out[ofs + 3] = v.w;
          return out;
        }
        static fromArray(out, arr, ofs = 0) {
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        }
        static strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          const inf = Infinity;
          const hasInf = abs$6(a.x) === inf || abs$6(a.y) === inf || abs$6(a.z) === inf || abs$6(a.w) === inf || abs$6(b.x) === inf || abs$6(b.y) === inf || abs$6(b.z) === inf || abs$6(b.w) === inf;
          return !hasInf && abs$6(a.x - b.x) <= epsilon * max$a(1.0, abs$6(a.x), abs$6(b.x)) && abs$6(a.y - b.y) <= epsilon * max$a(1.0, abs$6(a.y), abs$6(b.y)) && abs$6(a.z - b.z) <= epsilon * max$a(1.0, abs$6(a.z), abs$6(b.z)) && abs$6(a.w - b.w) <= epsilon * max$a(1.0, abs$6(a.w), abs$6(b.w));
        }
        constructor(x, y, z, w) {
          super();
          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;
          }
        }
        clone() {
          return new Vec4(this.x, this.y, this.z, this.w);
        }
        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;
        }
        equals(other, epsilon = EPSILON$2) {
          const self = this;
          return abs$6(self.x - other.x) <= epsilon * max$a(1.0, abs$6(self.x), abs$6(other.x)) && abs$6(self.y - other.y) <= epsilon * max$a(1.0, abs$6(self.y), abs$6(other.y)) && abs$6(self.z - other.z) <= epsilon * max$a(1.0, abs$6(self.z), abs$6(other.z)) && abs$6(self.w - other.w) <= epsilon * max$a(1.0, abs$6(self.w), abs$6(other.w));
        }
        equals4f(x, y, z, w, epsilon = EPSILON$2) {
          const self = this;
          return abs$6(self.x - x) <= epsilon * max$a(1.0, abs$6(self.x), abs$6(x)) && abs$6(self.y - y) <= epsilon * max$a(1.0, abs$6(self.y), abs$6(y)) && abs$6(self.z - z) <= epsilon * max$a(1.0, abs$6(self.z), abs$6(z)) && abs$6(self.w - w) <= epsilon * max$a(1.0, abs$6(self.w), abs$6(w));
        }
        strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        }
        strictEquals4f(x, y, z, w) {
          return this.x === x && this.y === y && this.z === z && this.w === w;
        }
        lerp(to, ratio) {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          const w = self.w;
          self.x = x + ratio * (to.x - x);
          self.y = y + ratio * (to.y - y);
          self.z = z + ratio * (to.z - z);
          self.w = w + ratio * (to.w - w);
          return self;
        }
        toString() {
          return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`;
        }
        clampf(minInclusive, maxInclusive) {
          const self = this;
          self.x = clamp$1(self.x, minInclusive.x, maxInclusive.x);
          self.y = clamp$1(self.y, minInclusive.y, maxInclusive.y);
          self.z = clamp$1(self.z, minInclusive.z, maxInclusive.z);
          self.w = clamp$1(self.w, minInclusive.w, maxInclusive.w);
          return self;
        }
        add(other) {
          const self = this;
          self.x += other.x;
          self.y += other.y;
          self.z += other.z;
          self.w += other.w;
          return self;
        }
        add4f(x, y, z, w) {
          const self = this;
          self.x += x;
          self.y += y;
          self.z += z;
          self.w += w;
          return self;
        }
        subtract(other) {
          const self = this;
          self.x -= other.x;
          self.y -= other.y;
          self.z -= other.z;
          self.w -= other.w;
          return self;
        }
        subtract4f(x, y, z, w) {
          const self = this;
          self.x -= x;
          self.y -= y;
          self.z -= z;
          self.w -= w;
          return self;
        }
        multiplyScalar(scalar) {
          const self = this;
          self.x *= scalar;
          self.y *= scalar;
          self.z *= scalar;
          self.w *= scalar;
          return self;
        }
        multiply(other) {
          const self = this;
          self.x *= other.x;
          self.y *= other.y;
          self.z *= other.z;
          self.w *= other.w;
          return self;
        }
        multiply4f(x, y, z, w) {
          const self = this;
          self.x *= x;
          self.y *= y;
          self.z *= z;
          self.w *= w;
          return self;
        }
        divide(other) {
          const self = this;
          self.x /= other.x;
          self.y /= other.y;
          self.z /= other.z;
          self.w /= other.w;
          return self;
        }
        divide4f(x, y, z, w) {
          const self = this;
          self.x /= x;
          self.y /= y;
          self.z /= z;
          self.w /= w;
          return self;
        }
        negative() {
          const self = this;
          self.x = -self.x;
          self.y = -self.y;
          self.z = -self.z;
          self.w = -self.w;
          return self;
        }
        dot(vector) {
          const self = this;
          return self.x * vector.x + self.y * vector.y + self.z * vector.z + self.w * vector.w;
        }
        cross(vector) {
          const self = this;
          const {
            x: ax,
            y: ay,
            z: az
          } = self;
          const {
            x: bx,
            y: by,
            z: bz
          } = vector;
          self.x = ay * bz - az * by;
          self.y = az * bx - ax * bz;
          self.z = ax * by - ay * bx;
          return self;
        }
        length() {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          const w = self.w;
          return sqrt$5(x * x + y * y + z * z + w * w);
        }
        lengthSqr() {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          const w = self.w;
          return x * x + y * y + z * z + w * w;
        }
        normalize() {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          const w = self.w;
          let len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / sqrt$5(len);
            self.x = x * len;
            self.y = y * len;
            self.z = z * len;
            self.w = w * len;
          }
          return self;
        }
        scale(scalar) {
          const self = this;
          self.x *= scalar;
          self.y *= scalar;
          self.z *= scalar;
          self.w *= scalar;
          return self;
        }
        transformMat4(matrix) {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          const w = self.w;
          self.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w;
          self.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w;
          self.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w;
          self.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w;
          return self;
        }
      } exports("Vec4", Vec4);
      _class$2y = Vec4;
      Vec4.ZERO = Object.freeze(new _class$2y(0, 0, 0, 0));
      Vec4.ONE = Object.freeze(new _class$2y(1, 1, 1, 1));
      Vec4.NEG_ONE = Object.freeze(new _class$2y(-1, -1, -1, -1));
      Vec4.UNIT_X = Object.freeze(new _class$2y(1, 0, 0, 0));
      Vec4.UNIT_Y = Object.freeze(new _class$2y(0, 1, 0, 0));
      Vec4.UNIT_Z = Object.freeze(new _class$2y(0, 0, 1, 0));
      Vec4.UNIT_W = Object.freeze(new _class$2y(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$2x;
      const abs$5 = Math.abs;
      const max$9 = Math.max;
      const min$6 = Math.min;
      const PI$4 = Math.PI;
      const acos$4 = Math.acos;
      const sin$5 = Math.sin;
      const cos$6 = Math.cos;
      const sqrt$4 = Math.sqrt;
      const ceil$3 = Math.ceil;
      const floor$1 = Math.floor;
      const round$1 = Math.round;
      class Vec3 extends ValueType {
        static zero(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          return out;
        }
        static clone(a) {
          return new Vec3(a.x, a.y, a.z);
        }
        static copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          return out;
        }
        static set(out, x, y, z) {
          out.x = x;
          out.y = y;
          out.z = z;
          return out;
        }
        static add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          out.z = a.z + b.z;
          return out;
        }
        static subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          out.z = a.z - b.z;
          return out;
        }
        static multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          out.z = a.z * b.z;
          return out;
        }
        static divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          out.z = a.z / b.z;
          return out;
        }
        static ceil(out, a) {
          out.x = ceil$3(a.x);
          out.y = ceil$3(a.y);
          out.z = ceil$3(a.z);
          return out;
        }
        static floor(out, a) {
          out.x = floor$1(a.x);
          out.y = floor$1(a.y);
          out.z = floor$1(a.z);
          return out;
        }
        static min(out, a, b) {
          out.x = min$6(a.x, b.x);
          out.y = min$6(a.y, b.y);
          out.z = min$6(a.z, b.z);
          return out;
        }
        static max(out, a, b) {
          out.x = max$9(a.x, b.x);
          out.y = max$9(a.y, b.y);
          out.z = max$9(a.z, b.z);
          return out;
        }
        static round(out, a) {
          out.x = round$1(a.x);
          out.y = round$1(a.y);
          out.z = round$1(a.z);
          return out;
        }
        static multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          return out;
        }
        static 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;
        }
        static distance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          const z = b.z - a.z;
          return sqrt$4(x * x + y * y + z * z);
        }
        static squaredDistance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          const z = b.z - a.z;
          return x * x + y * y + z * z;
        }
        static len(a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          return sqrt$4(x * x + y * y + z * z);
        }
        static lengthSqr(a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          return x * x + y * y + z * z;
        }
        static negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          return out;
        }
        static invert(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          out.z = 1.0 / a.z;
          return out;
        }
        static invertSafe(out, a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          if (abs$5(x) < EPSILON$2) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (abs$5(y) < EPSILON$2) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (abs$5(z) < EPSILON$2) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          return out;
        }
        static normalize(out, a) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          let len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / sqrt$4(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;
        }
        static dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z;
        }
        static cross(out, a, b) {
          const {
            x: ax,
            y: ay,
            z: az
          } = a;
          const {
            x: bx,
            y: by,
            z: bz
          } = b;
          out.x = ay * bz - az * by;
          out.y = az * bx - ax * bz;
          out.z = ax * by - ay * bx;
          return out;
        }
        static 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;
        }
        static random(out, scale) {
          scale = scale || 1.0;
          const phi = random() * 2.0 * PI$4;
          const cosTheta = random() * 2 - 1;
          const sinTheta = sqrt$4(1 - cosTheta * cosTheta);
          out.x = sinTheta * cos$6(phi) * scale;
          out.y = sinTheta * sin$5(phi) * scale;
          out.z = cosTheta * scale;
          return out;
        }
        static transformMat4(out, a, m) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          let 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;
        }
        static transformMat4Normal(out, a, m) {
          const x = a.x;
          const y = a.y;
          const z = a.z;
          let 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;
        }
        static transformMat3(out, a, m) {
          const x = a.x;
          const y = a.y;
          const 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;
        }
        static transformAffine(out, v, m) {
          const x = v.x;
          const y = v.y;
          const 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;
        }
        static transformQuat(out, a, q) {
          const ix = q.w * a.x + q.y * a.z - q.z * a.y;
          const iy = q.w * a.y + q.z * a.x - q.x * a.z;
          const iz = q.w * a.z + q.x * a.y - q.y * a.x;
          const 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;
        }
        static transformRTS(out, a, r, t, s) {
          const x = a.x * s.x;
          const y = a.y * s.y;
          const z = a.z * s.z;
          const ix = r.w * x + r.y * z - r.z * y;
          const iy = r.w * y + r.z * x - r.x * z;
          const iz = r.w * z + r.x * y - r.y * x;
          const 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;
        }
        static transformInverseRTS(out, a, r, t, s) {
          const x = a.x - t.x;
          const y = a.y - t.y;
          const z = a.z - t.z;
          const ix = r.w * x - r.y * z + r.z * y;
          const iy = r.w * y - r.z * x + r.x * z;
          const iz = r.w * z - r.x * y + r.y * x;
          const 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;
        }
        static rotateX(out, v, o, a) {
          const x = v.x - o.x;
          const y = v.y - o.y;
          const z = v.z - o.z;
          const c = cos$6(a);
          const s = sin$5(a);
          const rx = x;
          const ry = y * c - z * s;
          const rz = y * s + z * c;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        }
        static rotateY(out, v, o, a) {
          const x = v.x - o.x;
          const y = v.y - o.y;
          const z = v.z - o.z;
          const c = cos$6(a);
          const s = sin$5(a);
          const rx = z * s + x * c;
          const ry = y;
          const rz = z * c - x * s;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        }
        static rotateZ(out, v, o, a) {
          const x = v.x - o.x;
          const y = v.y - o.y;
          const z = v.z - o.z;
          const c = cos$6(a);
          const s = sin$5(a);
          const rx = x * c - y * s;
          const ry = x * s + y * c;
          const rz = z;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        }
        static rotateN(out, v, o, n, a) {
          const x = v.x - o.x;
          const y = v.y - o.y;
          const z = v.z - o.z;
          const nx = n.x;
          const ny = n.y;
          const nz = n.z;
          const c = cos$6(a);
          const s = sin$5(a);
          const rx = x * (nx * nx * (1.0 - c) + c) + y * (nx * ny * (1.0 - c) - nz * s) + z * (nx * nz * (1.0 - c) + ny * s);
          const ry = x * (nx * ny * (1.0 - c) + nz * s) + y * (ny * ny * (1.0 - c) + c) + z * (ny * nz * (1.0 - c) - nx * s);
          const rz = x * (nx * nz * (1.0 - c) - ny * s) + y * (ny * nz * (1.0 - c) + nx * s) + z * (nz * nz * (1.0 - c) + c);
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        }
        static toArray(out, v, ofs = 0) {
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          return out;
        }
        static fromArray(out, arr, ofs = 0) {
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          return out;
        }
        static strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          const {
            x: a0,
            y: a1,
            z: a2
          } = a;
          const {
            x: b0,
            y: b1,
            z: b2
          } = b;
          return abs$5(a0 - b0) <= epsilon * max$9(1.0, abs$5(a0), abs$5(b0)) && abs$5(a1 - b1) <= epsilon * max$9(1.0, abs$5(a1), abs$5(b1)) && abs$5(a2 - b2) <= epsilon * max$9(1.0, abs$5(a2), abs$5(b2));
        }
        static angle(a, b) {
          const magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z;
          const magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          const dot = a.x * b.x + a.y * b.y + a.z * b.z;
          let cosine = dot / sqrt$4(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return acos$4(cosine);
        }
        static projectOnPlane(out, a, n) {
          return Vec3.subtract(out, a, Vec3.project(out, a, n));
        }
        static project(out, a, b) {
          const 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);
          }
        }
        static moveTowards(out, current, target, maxStep) {
          const deltaX = target.x - current.x;
          const deltaY = target.y - current.y;
          const deltaZ = target.z - current.z;
          const 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;
          }
          const distance = sqrt$4(distanceSqr);
          const scale = maxStep / distance;
          out.x = current.x + deltaX * scale;
          out.y = current.y + deltaY * scale;
          out.z = current.z + deltaZ * scale;
          return out;
        }
        static generateOrthogonal(out, n) {
          const {
            x,
            y,
            z
          } = n;
          const absX = abs$5(x);
          const absY = abs$5(y);
          const absZ = abs$5(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);
        }
        constructor(x, y, z) {
          super();
          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;
          }
        }
        clone() {
          return new Vec3(this.x, this.y, this.z);
        }
        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;
        }
        equals(other, epsilon = EPSILON$2) {
          return abs$5(this.x - other.x) <= epsilon && abs$5(this.y - other.y) <= epsilon && abs$5(this.z - other.z) <= epsilon;
        }
        equals3f(x, y, z, epsilon = EPSILON$2) {
          return abs$5(this.x - x) <= epsilon && abs$5(this.y - y) <= epsilon && abs$5(this.z - z) <= epsilon;
        }
        strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z;
        }
        strictEquals3f(x, y, z) {
          return this.x === x && this.y === y && this.z === z;
        }
        toString() {
          return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)})`;
        }
        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;
        }
        add(other) {
          this.x += other.x;
          this.y += other.y;
          this.z += other.z;
          return this;
        }
        add3f(x, y, z) {
          this.x += x;
          this.y += y;
          this.z += z;
          return this;
        }
        subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          this.z -= other.z;
          return this;
        }
        subtract3f(x, y, z) {
          this.x -= x;
          this.y -= y;
          this.z -= z;
          return this;
        }
        multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            warnID(16357);
          }
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          return this;
        }
        multiply(other) {
          if (typeof other !== 'object') {
            warnID(16358);
          }
          this.x *= other.x;
          this.y *= other.y;
          this.z *= other.z;
          return this;
        }
        multiply3f(x, y, z) {
          this.x *= x;
          this.y *= y;
          this.z *= z;
          return this;
        }
        divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          this.z /= other.z;
          return this;
        }
        divide3f(x, y, z) {
          this.x /= x;
          this.y /= y;
          this.z /= z;
          return this;
        }
        negative() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          return this;
        }
        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;
        }
        dot(other) {
          return this.x * other.x + this.y * other.y + this.z * other.z;
        }
        cross(other) {
          const {
            x: ax,
            y: ay,
            z: az
          } = this;
          const {
            x: bx,
            y: by,
            z: bz
          } = other;
          this.x = ay * bz - az * by;
          this.y = az * bx - ax * bz;
          this.z = ax * by - ay * bx;
          return this;
        }
        length() {
          const self = this;
          return sqrt$4(self.x * self.x + self.y * self.y + self.z * self.z);
        }
        lengthSqr() {
          const self = this;
          return self.x * self.x + self.y * self.y + self.z * self.z;
        }
        normalize() {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          let len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / sqrt$4(len);
            self.x = x * len;
            self.y = y * len;
            self.z = z * len;
          }
          return self;
        }
        transformMat4(matrix) {
          const self = this;
          const x = self.x;
          const y = self.y;
          const z = self.z;
          let rhw = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15;
          rhw = rhw ? 1 / rhw : 1;
          self.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw;
          self.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw;
          self.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw;
          return self;
        }
        toVec2() {
          return new legacyCC.Vec2(this.x, this.y);
        }
      } exports("Vec3", Vec3);
      _class$2x = Vec3;
      Vec3.UNIT_X = Object.freeze(new _class$2x(1, 0, 0));
      Vec3.UNIT_Y = Object.freeze(new _class$2x(0, 1, 0));
      Vec3.UNIT_Z = Object.freeze(new _class$2x(0, 0, 1));
      Vec3.RIGHT = Object.freeze(new _class$2x(1, 0, 0));
      Vec3.UP = Object.freeze(new _class$2x(0, 1, 0));
      Vec3.FORWARD = Object.freeze(new _class$2x(0, 0, -1));
      Vec3.ZERO = Object.freeze(new _class$2x(0, 0, 0));
      Vec3.ONE = Object.freeze(new _class$2x(1, 1, 1));
      Vec3.NEG_ONE = Object.freeze(new _class$2x(-1, -1, -1));
      Vec3.slerp = (() => {
        const cacheV1 = new _class$2x();
        const cacheV2 = new _class$2x();
        const cacheV3 = new _class$2x();
        return (out, from, to, t) => {
          const EPSILON = 1e-5;
          const lenFrom = _class$2x.len(from);
          const lenTo = _class$2x.len(to);
          if (lenFrom < EPSILON || lenTo < EPSILON) {
            return _class$2x.lerp(out, from, to, t);
          }
          const lenLerped = lerp(lenFrom, lenTo, t);
          const dot = _class$2x.dot(from, to) / (lenFrom * lenTo);
          if (dot > 1.0 - EPSILON) {
            return _class$2x.lerp(out, from, to, t);
          } else if (dot < -1.0 + EPSILON) {
            const fromNormalized = _class$2x.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            const axis = _class$2x.generateOrthogonal(cacheV2, fromNormalized);
            const angle = PI$4 * t;
            rotateAxisAngle(cacheV3, fromNormalized, axis, angle);
            _class$2x.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          } else {
            const dotClamped = dot;
            const theta = acos$4(dotClamped) * t;
            const fromNormalized = _class$2x.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            const toNormalized = _class$2x.multiplyScalar(cacheV2, to, 1.0 / lenTo);
            _class$2x.scaleAndAdd(cacheV3, toNormalized, fromNormalized, -dotClamped);
            _class$2x.normalize(cacheV3, cacheV3);
            _class$2x.multiplyScalar(cacheV3, cacheV3, sin$5(theta));
            _class$2x.scaleAndAdd(cacheV3, cacheV3, fromNormalized, cos$6(theta));
            _class$2x.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          }
        };
      })();
      Vec3.signedAngle = (() => {
        const cacheCross = new _class$2x();
        return (a, b, normal) => {
          const angle = _class$2x.angle(a, b);
          const cross = _class$2x.cross(cacheCross, a, b);
          const dot = _class$2x.dot(cross, normal);
          return dot < 0 ? -angle : angle;
        };
      })();
      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);
      }
      const rotateAxisAngle = (() => {
        const cacheQ = {
          x: 0.0,
          y: 0.0,
          z: 0.0,
          w: 0.0
        };
        return (out, input, axis, angle) => {
          const rad = angle * 0.5;
          const s = sin$5(rad);
          cacheQ.x = s * axis.x;
          cacheQ.y = s * axis.y;
          cacheQ.z = s * axis.z;
          cacheQ.w = cos$6(rad);
          Vec3.transformQuat(out, input, cacheQ);
          return out;
        };
      })();
      legacyCC.v3 = v3;

      var _class$2w;
      const toFloat = 1 / 255;
      const R_INDEX = 0;
      const G_INDEX = 1;
      const B_INDEX = 2;
      const A_INDEX = 3;
      let Color$1 = class Color extends ValueType {
        static clone(a) {
          const out = new Color();
          out.r = a.r;
          out.g = a.g;
          out.b = a.b;
          out.a = a.a;
          return out;
        }
        static copy(out, a) {
          out.r = a.r;
          out.g = a.g;
          out.b = a.b;
          out.a = a.a;
          return out;
        }
        static set(out, r, g, b, a) {
          out.r = r;
          out.g = g;
          out.b = b;
          out.a = a;
          return out;
        }
        static toVec4(color, out) {
          out = out !== undefined ? out : new Vec4();
          out.x = color._data[R_INDEX] * toFloat;
          out.y = color._data[G_INDEX] * toFloat;
          out.z = color._data[B_INDEX] * toFloat;
          out.w = color._data[A_INDEX] * toFloat;
          return out;
        }
        static fromVec4(value, out) {
          out = out === undefined ? new Color() : out;
          out._data[R_INDEX] = value.x / toFloat;
          out._data[G_INDEX] = value.y / toFloat;
          out._data[B_INDEX] = value.z / toFloat;
          out._data[A_INDEX] = value.w / toFloat;
          return out;
        }
        static fromHEX(out, hex) {
          let hexNumber;
          if (typeof hex === 'string') {
            hex = hex[0] === '#' ? hex.substring(1) : hex;
            if (hex.length === 6) {
              hex += 'FF';
            } else if (hex.length === 3) {
              hex = `${hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]}FF`;
            } else if (hex.length === 4) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
            }
            hexNumber = Number(`0x${hex}`);
          } else {
            if (hex < 0x1000000) {
              hex = (hex << 8) + 0xff;
            }
            hexNumber = hex;
          }
          out.r = hexNumber >>> 24;
          out.g = (hexNumber & 0x00ff0000) >>> 16;
          out.b = (hexNumber & 0x0000ff00) >>> 8;
          out.a = hexNumber & 0x000000ff;
          return out;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static lerp(out, from, to, ratio) {
          const fromR = from.r;
          const fromG = from.g;
          const fromB = from.b;
          const fromA = from.a;
          out.r = fromR + (to.r - fromR) * ratio;
          out.g = fromG + (to.g - fromG) * ratio;
          out.b = fromB + (to.b - fromB) * ratio;
          out.a = fromA + (to.a - fromA) * ratio;
          return out;
        }
        static toArray(out, a, ofs = 0) {
          const 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;
        }
        static fromArray(arr, out, 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;
        }
        static fromUint32(out, uint32) {
          uint32 >>>= 0;
          out.r = uint32 & 0xff;
          out.g = uint32 >> 8 & 0xff;
          out.b = uint32 >> 16 & 0xff;
          out.a = uint32 >> 24 & 0xff;
          return out;
        }
        static toUint32(color) {
          return (color.a << 24 | color.b << 16 | color.g << 8 | color.r) >>> 0;
        }
        static strictEquals(a, b) {
          return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          const 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));
        }
        static hex(a) {
          return (a.r * 255 << 24 | a.g * 255 << 16 | a.b * 255 << 8 | a.a * 255) >>> 0;
        }
        get r() {
          return this._data[R_INDEX];
        }
        set r(red) {
          this._data[R_INDEX] = red;
        }
        get g() {
          return this._data[G_INDEX];
        }
        set g(green) {
          this._data[G_INDEX] = green;
        }
        get b() {
          return this._data[B_INDEX];
        }
        set b(blue) {
          this._data[B_INDEX] = blue;
        }
        get a() {
          return this._data[A_INDEX];
        }
        set a(alpha) {
          this._data[A_INDEX] = alpha;
        }
        get x() {
          return this._data[R_INDEX] * toFloat;
        }
        set x(value) {
          this._data[R_INDEX] = value * 255;
        }
        get y() {
          return this._data[G_INDEX] * toFloat;
        }
        set y(value) {
          this._data[G_INDEX] = value * 255;
        }
        get z() {
          return this._data[B_INDEX] * toFloat;
        }
        set z(value) {
          this._data[B_INDEX] = value * 255;
        }
        get w() {
          return this._data[A_INDEX] * toFloat;
        }
        set w(value) {
          this._data[A_INDEX] = value * 255;
        }
        constructor(r, g, b, a) {
          super();
          this._data = new Uint8ClampedArray(4);
          if (typeof r === 'string') {
            this.fromHEX(r);
          } else if (g !== undefined) {
            this.set(r, g, b, a);
          } else {
            this.set(r);
          }
        }
        clone() {
          const ret = new Color();
          ret._data.set(this._data);
          return ret;
        }
        equals(other) {
          const otherColor = other;
          return other && this._data[R_INDEX] === otherColor.r && this._data[G_INDEX] === otherColor.g && this._data[B_INDEX] === otherColor.b && this._data[A_INDEX] === otherColor.a;
        }
        lerp(to, ratio) {
          Color.lerp(this, this, to, ratio);
          return this;
        }
        toString() {
          return `rgba(${this.r.toFixed()}, ${this.g.toFixed()}, ${this.b.toFixed()}, ${this.a.toFixed()})`;
        }
        toCSS(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)}`;
          }
        }
        fromHEX(hex) {
          let hexNumber;
          if (typeof hex === 'string') {
            hex = hex[0] === '#' ? hex.substring(1) : hex;
            if (hex.length === 6) {
              hex += 'FF';
            } else if (hex.length === 3) {
              hex = `${hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]}FF`;
            } else if (hex.length === 4) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
            }
            hexNumber = Number(`0x${hex}`);
          } else {
            if (hex < 0x1000000) {
              hex = (hex << 8) + 0xff;
            }
            hexNumber = hex;
          }
          this.r = hexNumber >>> 24;
          this.g = (hexNumber & 0x00ff0000) >>> 16;
          this.b = (hexNumber & 0x0000ff00) >>> 8;
          this.a = hexNumber & 0x000000ff;
          return this;
        }
        toHEX(fmt = '#rrggbb') {
          const prefix = '0';
          const hex = [(this._data[R_INDEX] < 16 ? prefix : '') + this._data[R_INDEX].toString(16), (this._data[G_INDEX] < 16 ? prefix : '') + this._data[G_INDEX].toString(16), (this._data[B_INDEX] < 16 ? prefix : '') + this._data[B_INDEX].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._data[A_INDEX] < 16 ? prefix : '') + this._data[A_INDEX].toString(16));
          }
          return hex.join('');
        }
        toRGBValue() {
          return this._data[B_INDEX] << 16 | this._data[G_INDEX] << 8 | this._data[R_INDEX];
        }
        fromHSV(h, s, v) {
          let r = 0;
          let g = 0;
          let 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;
            const i = Math.floor(h);
            const f = h - i;
            const p = v * (1 - s);
            const q = v * (1 - s * f);
            const t = v * (1 - s * (1 - f));
            switch (i) {
              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;
            }
          }
          this._data[R_INDEX] = r * 255;
          this._data[G_INDEX] = g * 255;
          this._data[B_INDEX] = b * 255;
          return this;
        }
        toHSV() {
          const r = this._data[R_INDEX] * toFloat;
          const g = this._data[G_INDEX] * toFloat;
          const b = this._data[B_INDEX] * toFloat;
          const hsv = {
            h: 0,
            s: 0,
            v: 0
          };
          const max = Math.max(r, g, b);
          const min = Math.min(r, g, b);
          let 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;
        }
        set(r, g, b, a) {
          if (typeof r === 'object') {
            const other = r;
            if (other._data) {
              this._data.set(other._data);
            } else {
              var _other$r, _other$g, _other$b, _other$a;
              this._data[R_INDEX] = (_other$r = other.r) !== null && _other$r !== void 0 ? _other$r : 0;
              this._data[G_INDEX] = (_other$g = other.g) !== null && _other$g !== void 0 ? _other$g : 0;
              this._data[B_INDEX] = (_other$b = other.b) !== null && _other$b !== void 0 ? _other$b : 0;
              this._data[A_INDEX] = (_other$a = other.a) !== null && _other$a !== void 0 ? _other$a : 255;
            }
          } else {
            this._data[R_INDEX] = r !== null && r !== void 0 ? r : 0;
            this._data[G_INDEX] = g !== null && g !== void 0 ? g : 0;
            this._data[B_INDEX] = b !== null && b !== void 0 ? b : 0;
            this._data[A_INDEX] = a !== null && a !== void 0 ? a : 255;
          }
          return this;
        }
        multiply(other) {
          this._data[R_INDEX] *= other.r / 255;
          this._data[G_INDEX] *= other.g / 255;
          this._data[B_INDEX] *= other.b / 255;
          this._data[A_INDEX] *= other.a / 255;
          return this;
        }
        getModifiableProperties() {
          return ['r', 'g', 'b', 'a'];
        }
      }; exports("Color", Color$1);
      _class$2w = Color$1;
      Color$1.WHITE = Object.freeze(new _class$2w(255, 255, 255, 255));
      Color$1.GRAY = Object.freeze(new _class$2w(127, 127, 127, 255));
      Color$1.BLACK = Object.freeze(new _class$2w(0, 0, 0, 255));
      Color$1.TRANSPARENT = Object.freeze(new _class$2w(0, 0, 0, 0));
      Color$1.RED = Object.freeze(new _class$2w(255, 0, 0, 255));
      Color$1.GREEN = Object.freeze(new _class$2w(0, 255, 0, 255));
      Color$1.BLUE = Object.freeze(new _class$2w(0, 0, 255, 255));
      Color$1.CYAN = Object.freeze(new _class$2w(0, 255, 255, 255));
      Color$1.MAGENTA = Object.freeze(new _class$2w(255, 0, 255, 255));
      Color$1.YELLOW = Object.freeze(new _class$2w(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;

      var _class$2v;
      const abs$4 = Math.abs;
      const max$8 = Math.max;
      class Mat3 extends ValueType {
        static clone(a) {
          return new Mat3(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08);
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static transpose(out, a) {
          if (out === a) {
            const a01 = a.m01;
            const a02 = a.m02;
            const 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;
        }
        static invert(out, a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          const b01 = a22 * a11 - a12 * a21;
          const b11 = -a22 * a10 + a12 * a20;
          const b21 = a21 * a10 - a11 * a20;
          let det = a00 * b01 + a01 * b11 + a02 * b21;
          if (det === 0) {
            Mat3.set(out, 0, 0, 0, 0, 0, 0, 0, 0, 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;
        }
        static determinant(a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
        }
        static multiply(out, a, b) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          const b00 = b.m00;
          const b01 = b.m01;
          const b02 = b.m02;
          const b10 = b.m03;
          const b11 = b.m04;
          const b12 = b.m05;
          const b20 = b.m06;
          const b21 = b.m07;
          const 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;
        }
        static multiplyMat4(out, a, b) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          const b00 = b.m00;
          const b01 = b.m01;
          const b02 = b.m02;
          const b10 = b.m04;
          const b11 = b.m05;
          const b12 = b.m06;
          const b20 = b.m08;
          const b21 = b.m09;
          const 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;
        }
        static transform(out, a, v) {
          this.translate(out, a, v);
        }
        static translate(out, a, v) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          const x = v.x;
          const 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;
        }
        static scale(out, a, v) {
          const x = v.x;
          const 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;
        }
        static rotate(out, a, rad) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a10 = a.m03;
          const a11 = a.m04;
          const a12 = a.m05;
          const a20 = a.m06;
          const a21 = a.m07;
          const a22 = a.m08;
          const s = Math.sin(rad);
          const 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;
        }
        static 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;
        }
        static fromViewUp(out, view, up) {
          if (Vec3.lengthSqr(view) < EPSILON$2 * EPSILON$2) {
            Mat3.identity(out);
            return out;
          }
          up = up || Vec3.UNIT_Y;
          Vec3.normalize(v3_1$3, Vec3.cross(v3_1$3, up, view));
          if (Vec3.lengthSqr(v3_1$3) < EPSILON$2 * EPSILON$2) {
            Mat3.identity(out);
            return out;
          }
          Vec3.cross(v3_2, view, v3_1$3);
          Mat3.set(out, v3_1$3.x, v3_1$3.y, v3_1$3.z, v3_2.x, v3_2.y, v3_2.z, view.x, view.y, view.z);
          return out;
        }
        static 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;
        }
        static 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;
        }
        static fromRotation(out, rad) {
          const s = Math.sin(rad);
          const 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;
        }
        static fromQuat(out, q) {
          const x = q.x;
          const y = q.y;
          const z = q.z;
          const w = q.w;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const yx = y * x2;
          const yy = y * y2;
          const zx = z * x2;
          const zy = z * y2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const 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;
        }
        static inverseTransposeMat4(out, a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const a30 = a.m12;
          const a31 = a.m13;
          const a32 = a.m14;
          const a33 = a.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          let 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;
        }
        static toArray(out, m, 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;
        }
        static fromArray(out, arr, 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          return abs$4(a.m00 - b.m00) <= epsilon * max$8(1.0, abs$4(a.m00), abs$4(b.m00)) && abs$4(a.m01 - b.m01) <= epsilon * max$8(1.0, abs$4(a.m01), abs$4(b.m01)) && abs$4(a.m02 - b.m02) <= epsilon * max$8(1.0, abs$4(a.m02), abs$4(b.m02)) && abs$4(a.m03 - b.m03) <= epsilon * max$8(1.0, abs$4(a.m03), abs$4(b.m03)) && abs$4(a.m04 - b.m04) <= epsilon * max$8(1.0, abs$4(a.m04), abs$4(b.m04)) && abs$4(a.m05 - b.m05) <= epsilon * max$8(1.0, abs$4(a.m05), abs$4(b.m05)) && abs$4(a.m06 - b.m06) <= epsilon * max$8(1.0, abs$4(a.m06), abs$4(b.m06)) && abs$4(a.m07 - b.m07) <= epsilon * max$8(1.0, abs$4(a.m07), abs$4(b.m07)) && abs$4(a.m08 - b.m08) <= epsilon * max$8(1.0, abs$4(a.m08), abs$4(b.m08));
        }
        static toEuler(matrix, v) {
          const a00 = matrix.m00;
          const a01 = matrix.m01;
          matrix.m02;
          const a10 = matrix.m03;
          const a11 = matrix.m04;
          matrix.m05;
          const a20 = matrix.m06;
          const a21 = matrix.m07;
          const 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;
          }
        }
        constructor(m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1) {
          super();
          const self = this;
          if (typeof m00 === 'object') {
            self.m00 = m00.m00;
            self.m01 = m00.m01;
            self.m02 = m00.m02;
            self.m03 = m00.m03;
            self.m04 = m00.m04;
            self.m05 = m00.m05;
            self.m06 = m00.m06;
            self.m07 = m00.m07;
            self.m08 = m00.m08;
          } else {
            self.m00 = m00;
            self.m01 = m01;
            self.m02 = m02;
            self.m03 = m03;
            self.m04 = m04;
            self.m05 = m05;
            self.m06 = m06;
            self.m07 = m07;
            self.m08 = m08;
          }
        }
        clone() {
          return new Mat3(this);
        }
        set(m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1) {
          const self = this;
          if (typeof m00 === 'object') {
            self.m00 = m00.m00;
            self.m01 = m00.m01;
            self.m02 = m00.m02;
            self.m03 = m00.m03;
            self.m04 = m00.m04;
            self.m05 = m00.m05;
            self.m06 = m00.m06;
            self.m07 = m00.m07;
            self.m08 = m00.m08;
          } else {
            self.m00 = m00;
            self.m01 = m01;
            self.m02 = m02;
            self.m03 = m03;
            self.m04 = m04;
            self.m05 = m05;
            self.m06 = m06;
            self.m07 = m07;
            self.m08 = m08;
          }
          return self;
        }
        equals(other, epsilon = EPSILON$2) {
          return Mat3.equals(this, other, epsilon);
        }
        strictEquals(other) {
          return Mat3.strictEquals(this, other);
        }
        toString() {
          const 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` + `]`;
        }
        identity() {
          return Mat3.identity(this);
        }
        transpose() {
          const self = this;
          const a01 = self.m01;
          const a02 = self.m02;
          const a12 = self.m05;
          self.m01 = self.m03;
          self.m02 = self.m06;
          self.m03 = a01;
          self.m05 = self.m07;
          self.m06 = a02;
          self.m07 = a12;
          return self;
        }
        invert() {
          return Mat3.invert(this, this);
        }
        determinant() {
          return Mat3.determinant(this);
        }
        add(mat) {
          const self = this;
          self.m00 += mat.m00;
          self.m01 += mat.m01;
          self.m02 += mat.m02;
          self.m03 += mat.m03;
          self.m04 += mat.m04;
          self.m05 += mat.m05;
          self.m06 += mat.m06;
          self.m07 += mat.m07;
          self.m08 += mat.m08;
          return self;
        }
        subtract(mat) {
          const self = this;
          self.m00 -= mat.m00;
          self.m01 -= mat.m01;
          self.m02 -= mat.m02;
          self.m03 -= mat.m03;
          self.m04 -= mat.m04;
          self.m05 -= mat.m05;
          self.m06 -= mat.m06;
          self.m07 -= mat.m07;
          self.m08 -= mat.m08;
          return self;
        }
        multiply(mat) {
          return Mat3.multiply(this, this, mat);
        }
        multiplyScalar(scalar) {
          const self = this;
          self.m00 *= scalar;
          self.m01 *= scalar;
          self.m02 *= scalar;
          self.m03 *= scalar;
          self.m04 *= scalar;
          self.m05 *= scalar;
          self.m06 *= scalar;
          self.m07 *= scalar;
          self.m08 *= scalar;
          return self;
        }
        scale(vec) {
          const x = vec.x;
          const y = vec.y;
          const self = this;
          self.m00 *= x;
          self.m01 *= x;
          self.m02 *= x;
          self.m03 *= y;
          self.m04 *= y;
          self.m05 *= y;
          return self;
        }
        rotate(rad) {
          const self = this;
          const a00 = self.m00;
          const a01 = self.m01;
          const a02 = self.m02;
          const a10 = self.m03;
          const a11 = self.m04;
          const a12 = self.m05;
          const a20 = self.m06;
          const a21 = self.m07;
          const a22 = self.m08;
          const s = Math.sin(rad);
          const c = Math.cos(rad);
          self.m00 = c * a00 + s * a10;
          self.m01 = c * a01 + s * a11;
          self.m02 = c * a02 + s * a12;
          self.m03 = c * a10 - s * a00;
          self.m04 = c * a11 - s * a01;
          self.m05 = c * a12 - s * a02;
          self.m06 = a20;
          self.m07 = a21;
          self.m08 = a22;
          return self;
        }
        fromQuat(q) {
          const x = q.x;
          const y = q.y;
          const z = q.z;
          const w = q.w;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const yx = y * x2;
          const yy = y * y2;
          const zx = z * x2;
          const zy = z * y2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const wz = w * z2;
          const self = this;
          self.m00 = 1 - yy - zz;
          self.m03 = yx - wz;
          self.m06 = zx + wy;
          self.m01 = yx + wz;
          self.m04 = 1 - xx - zz;
          self.m07 = zy - wx;
          self.m02 = zx - wy;
          self.m05 = zy + wx;
          self.m08 = 1 - xx - yy;
          return self;
        }
      } exports("Mat3", Mat3);
      _class$2v = Mat3;
      Mat3.IDENTITY = Object.freeze(new _class$2v());
      const v3_1$3 = new Vec3();
      const v3_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$2u;
      const abs$3 = Math.abs;
      const max$7 = Math.max;
      const min$5 = Math.min;
      const PI$3 = Math.PI;
      const acos$3 = Math.acos;
      const sin$4 = Math.sin;
      const cos$5 = Math.cos;
      const sqrt$3 = Math.sqrt;
      const atan2$2 = Math.atan2;
      const asin = Math.asin;
      const sign$1 = Math.sign;
      class Quat extends ValueType {
        static clone(a) {
          return new Quat(a.x, a.y, a.z, a.w);
        }
        static copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        }
        static set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        }
        static identity(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          out.w = 1;
          return out;
        }
        static rotationTo(out, a, b) {
          const dot = Vec3.dot(a, b);
          if (dot < -0.999999) {
            Vec3.cross(v3_1$2, Vec3.UNIT_X, a);
            if (v3_1$2.length() < 0.000001) {
              Vec3.cross(v3_1$2, Vec3.UNIT_Y, a);
            }
            Vec3.normalize(v3_1$2, v3_1$2);
            Quat.fromAxisAngle(out, v3_1$2, PI$3);
            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$2, a, b);
            out.x = v3_1$2.x;
            out.y = v3_1$2.y;
            out.z = v3_1$2.z;
            out.w = 1 + dot;
            return Quat.normalize(out, out);
          }
        }
        static getAxisAngle(outAxis, q) {
          const rad = acos$3(q.w) * 2.0;
          const s = sin$4(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;
        }
        static multiply(out, a, b) {
          const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
          const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
          const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
          const 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;
        }
        static 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;
        }
        static 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;
        }
        static rotateX(out, a, rad) {
          rad *= 0.5;
          const bx = sin$4(rad);
          const bw = cos$5(rad);
          const {
            x,
            y,
            z,
            w
          } = a;
          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;
        }
        static rotateY(out, a, rad) {
          rad *= 0.5;
          const by = sin$4(rad);
          const bw = cos$5(rad);
          const {
            x,
            y,
            z,
            w
          } = a;
          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;
        }
        static rotateZ(out, a, rad) {
          rad *= 0.5;
          const bz = sin$4(rad);
          const bw = cos$5(rad);
          const {
            x,
            y,
            z,
            w
          } = a;
          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;
        }
        static rotateAround(out, rot, axis, rad) {
          Quat.invert(qt_1, rot);
          Vec3.transformQuat(v3_1$2, axis, qt_1);
          Quat.fromAxisAngle(qt_1, v3_1$2, rad);
          Quat.multiply(out, rot, qt_1);
          return out;
        }
        static rotateAroundLocal(out, rot, axis, rad) {
          Quat.fromAxisAngle(qt_1, axis, rad);
          Quat.multiply(out, rot, qt_1);
          return out;
        }
        static calculateW(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = sqrt$3(abs$3(1.0 - a.x * a.x - a.y * a.y - a.z * a.z));
          return out;
        }
        static dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        }
        static 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;
        }
        static slerp(out, a, b, t) {
          let scale0 = 0;
          let scale1 = 0;
          let bx = b.x;
          let by = b.y;
          let bz = b.z;
          let bw = b.w;
          let 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) {
            const omega = acos$3(cosom);
            const sinom = sin$4(omega);
            scale0 = sin$4((1.0 - t) * omega) / sinom;
            scale1 = sin$4(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;
        }
        static sqlerp(out, a, b, c, d, t) {
          Quat.slerp(qt_1, a, d, t);
          Quat.slerp(qt_2, b, c, t);
          Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t));
          return out;
        }
        static invert(out, a) {
          const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          const 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;
        }
        static conjugate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = a.w;
          return out;
        }
        static len(a) {
          return sqrt$3(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
        }
        static lengthSqr(a) {
          return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
        }
        static normalize(out, a) {
          let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          if (len > 0) {
            len = 1 / sqrt$3(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;
        }
        static fromAxes(out, xAxis, yAxis, zAxis) {
          Mat3.set(m3_1$1, 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$1));
        }
        static fromViewUp(out, view, up) {
          Mat3.fromViewUp(m3_1$1, view, up);
          return Quat.normalize(out, Quat.fromMat3(out, m3_1$1));
        }
        static fromAxisAngle(out, axis, rad) {
          rad *= 0.5;
          const s = sin$4(rad);
          out.x = s * axis.x;
          out.y = s * axis.y;
          out.z = s * axis.z;
          out.w = cos$5(rad);
          return out;
        }
        static fromMat3(out, m) {
          const {
            m00,
            m01,
            m02,
            m03: m10,
            m04: m11,
            m05: m12,
            m06: m20,
            m07: m21,
            m08: m22
          } = m;
          const fourXSquaredMinus1 = m00 - m11 - m22;
          const fourYSquaredMinus1 = m11 - m00 - m22;
          const fourZSquaredMinus1 = m22 - m00 - m11;
          const fourWSquaredMinus1 = m00 + m11 + m22;
          let biggestIndex = 0;
          let fourBiggestSquaredMinus1 = fourWSquaredMinus1;
          if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourXSquaredMinus1;
            biggestIndex = 1;
          }
          if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourYSquaredMinus1;
            biggestIndex = 2;
          }
          if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourZSquaredMinus1;
            biggestIndex = 3;
          }
          const biggestVal = sqrt$3(fourBiggestSquaredMinus1 + 1) * 0.5;
          const 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;
        }
        static fromEuler(out, x, y, z) {
          x *= halfToRad;
          y *= halfToRad;
          z *= halfToRad;
          const sx = sin$4(x);
          const cx = cos$5(x);
          const sy = sin$4(y);
          const cy = cos$5(y);
          const sz = sin$4(z);
          const cz = cos$5(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;
        }
        static fromAngleZ(out, z) {
          z *= halfToRad;
          out.x = out.y = 0;
          out.z = sin$4(z);
          out.w = cos$5(z);
          return out;
        }
        static toAxisX(out, q) {
          const fy = 2.0 * q.y;
          const 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;
        }
        static toAxisY(out, q) {
          const fx = 2.0 * q.x;
          const fy = 2.0 * q.y;
          const 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;
        }
        static toAxisZ(out, q) {
          const fx = 2.0 * q.x;
          const fy = 2.0 * q.y;
          const 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;
        }
        static toEuler(out, q, outerZ) {
          const {
            x,
            y,
            z,
            w
          } = q;
          let bank = 0;
          let heading = 0;
          let attitude = 0;
          const test = x * y + z * w;
          if (test > 0.499999) {
            bank = 0;
            heading = toDegree(2 * atan2$2(x, w));
            attitude = 90;
          } else if (test < -0.499999) {
            bank = 0;
            heading = -toDegree(2 * atan2$2(x, w));
            attitude = -90;
          } else {
            const sqx = x * x;
            const sqy = y * y;
            const sqz = z * z;
            bank = toDegree(atan2$2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));
            heading = toDegree(atan2$2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));
            attitude = toDegree(asin(2 * test));
            if (outerZ) {
              bank = -180 * sign$1(bank + 1e-6) + bank;
              heading = -180 * sign$1(heading + 1e-6) + heading;
              attitude = 180 * sign$1(attitude + 1e-6) - attitude;
            }
          }
          out.x = bank;
          out.y = heading;
          out.z = attitude;
          return out;
        }
        static toEulerInYXZOrder(out, q) {
          Mat3.fromQuat(m3_1$1, q);
          Mat3.toEuler(m3_1$1, out);
          out.x = toDegree(out.x);
          out.y = toDegree(out.y);
          out.z = toDegree(out.z);
        }
        static toArray(out, q, ofs = 0) {
          out[ofs + 0] = q.x;
          out[ofs + 1] = q.y;
          out[ofs + 2] = q.z;
          out[ofs + 3] = q.w;
          return out;
        }
        static fromArray(out, arr, ofs = 0) {
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        }
        static strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          return abs$3(a.x - b.x) <= epsilon * max$7(1.0, abs$3(a.x), abs$3(b.x)) && abs$3(a.y - b.y) <= epsilon * max$7(1.0, abs$3(a.y), abs$3(b.y)) && abs$3(a.z - b.z) <= epsilon * max$7(1.0, abs$3(a.z), abs$3(b.z)) && abs$3(a.w - b.w) <= epsilon * max$7(1.0, abs$3(a.w), abs$3(b.w));
        }
        static angle(a, b) {
          const dot = min$5(abs$3(Quat.dot(a, b)), 1.0);
          return acos$3(dot) * 2.0;
        }
        static rotateTowards(out, from, to, maxStep) {
          const 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;
          }
          const t = min$5(maxStep / toDegree(angle), 1.0);
          return Quat.slerp(out, from, to, t);
        }
        constructor(x, y, z, w) {
          super();
          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;
          }
        }
        clone() {
          return new Quat(this.x, this.y, this.z, this.w);
        }
        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;
        }
        equals(other, epsilon = EPSILON$2) {
          return Quat.equals(this, other, epsilon);
        }
        strictEquals(other) {
          return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        }
        getEulerAngles(out) {
          return Quat.toEuler(out, this);
        }
        lerp(to, ratio) {
          const self = this;
          self.x += ratio * (to.x - self.x);
          self.y += ratio * (to.y - self.y);
          self.z += ratio * (to.z - self.z);
          self.w += ratio * (to.w - self.w);
          return self;
        }
        slerp(to, ratio) {
          return Quat.slerp(this, this, to, ratio);
        }
        length() {
          const self = this;
          const {
            x,
            y,
            z,
            w
          } = self;
          return sqrt$3(x * x + y * y + z * z + w * w);
        }
        lengthSqr() {
          const self = this;
          const {
            x,
            y,
            z,
            w
          } = self;
          return x * x + y * y + z * z + w * w;
        }
      } exports("Quat", Quat);
      _class$2u = Quat;
      Quat.IDENTITY = Object.freeze(new _class$2u());
      const qt_1 = new Quat();
      const qt_2 = new Quat();
      const v3_1$2 = new Vec3();
      const m3_1$1 = new Mat3();
      const halfToRad = 0.5 * PI$3 / 180.0;
      CCClass.fastDefine('cc.Quat', Quat, {
        x: 0,
        y: 0,
        z: 0,
        w: 1
      });
      legacyCC.Quat = Quat;
      function quat(x = 0, y = 0, z = 0, w = 1) {
        return new Quat(x, y, z, w);
      }
      legacyCC.quat = quat;

      var _class$2t;
      const preTransforms = exports("preTransforms", 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])]));
      const abs$2 = Math.abs;
      const max$6 = Math.max;
      const sqrt$2 = Math.sqrt;
      const sin$3 = Math.sin;
      const cos$4 = Math.cos;
      const tan = Math.tan;
      class Mat4 extends ValueType {
        static 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);
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static zero(out) {
          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;
        }
        static transpose(out, a) {
          if (out === a) {
            const a01 = a.m01;
            const a02 = a.m02;
            const a03 = a.m03;
            const a12 = a.m06;
            const a13 = a.m07;
            const 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;
        }
        static invert(out, a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const a30 = a.m12;
          const a31 = a.m13;
          const a32 = a.m14;
          const a33 = a.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            return Mat4.zero(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;
        }
        static determinant(a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const a30 = a.m12;
          const a31 = a.m13;
          const a32 = a.m14;
          const a33 = a.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        }
        static multiply(out, a, b) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const a30 = a.m12;
          const a31 = a.m13;
          const a32 = a.m14;
          const a33 = a.m15;
          let b0 = b.m00;
          let b1 = b.m01;
          let b2 = b.m02;
          let 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;
        }
        static transform(out, a, v) {
          const x = v.x;
          const y = v.y;
          const 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 {
            const a00 = a.m00;
            const a01 = a.m01;
            const a02 = a.m02;
            const a03 = a.m03;
            const a10 = a.m04;
            const a11 = a.m05;
            const a12 = a.m06;
            const a13 = a.m07;
            const a20 = a.m08;
            const a21 = a.m09;
            const a22 = a.m10;
            const 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;
        }
        static 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;
        }
        static scale(out, a, v) {
          const x = v.x;
          const y = v.y;
          const 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;
        }
        static rotate(out, a, rad, axis) {
          let x = axis.x;
          let y = axis.y;
          let z = axis.z;
          let len = sqrt$2(x * x + y * y + z * z);
          if (abs$2(len) < EPSILON$2) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          const s = sin$3(rad);
          const c = cos$4(rad);
          const t = 1 - c;
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const b00 = x * x * t + c;
          const b01 = y * x * t + z * s;
          const b02 = z * x * t - y * s;
          const b10 = x * y * t - z * s;
          const b11 = y * y * t + c;
          const b12 = z * y * t + x * s;
          const b20 = x * z * t + y * s;
          const b21 = y * z * t - x * s;
          const 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;
        }
        static rotateX(out, a, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const 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;
        }
        static rotateY(out, a, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const 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;
        }
        static rotateZ(out, a, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const 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;
        }
        static fromTranslation(out, v) {
          Mat4.identity(out);
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          return out;
        }
        static fromScaling(out, v) {
          Mat4.identity(out);
          out.m00 = v.x;
          out.m05 = v.y;
          out.m10 = v.z;
          return out;
        }
        static fromRotation(out, rad, axis) {
          let x = axis.x;
          let y = axis.y;
          let z = axis.z;
          let len = sqrt$2(x * x + y * y + z * z);
          if (abs$2(len) < EPSILON$2) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          const s = sin$3(rad);
          const c = cos$4(rad);
          const 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;
        }
        static fromXRotation(out, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          Mat4.identity(out);
          out.m05 = c;
          out.m06 = s;
          out.m09 = -s;
          out.m10 = c;
          return out;
        }
        static fromYRotation(out, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          Mat4.identity(out);
          out.m00 = c;
          out.m02 = -s;
          out.m08 = s;
          out.m10 = c;
          return out;
        }
        static fromZRotation(out, rad) {
          const s = sin$3(rad);
          const c = cos$4(rad);
          Mat4.identity(out);
          out.m00 = c;
          out.m01 = s;
          out.m04 = -s;
          out.m05 = c;
          return out;
        }
        static fromRT(out, q, v) {
          const x = q.x;
          const y = q.y;
          const z = q.z;
          const w = q.w;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const xy = x * y2;
          const xz = x * z2;
          const yy = y * y2;
          const yz = y * z2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const 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;
        }
        static getTranslation(out, mat) {
          out.x = mat.m12;
          out.y = mat.m13;
          out.z = mat.m14;
          return out;
        }
        static getScaling(out, mat) {
          const m00 = m3_1.m00 = mat.m00;
          const m01 = m3_1.m01 = mat.m01;
          const m02 = m3_1.m02 = mat.m02;
          const m04 = m3_1.m03 = mat.m04;
          const m05 = m3_1.m04 = mat.m05;
          const m06 = m3_1.m05 = mat.m06;
          const m08 = m3_1.m06 = mat.m08;
          const m09 = m3_1.m07 = mat.m09;
          const m10 = m3_1.m08 = mat.m10;
          out.x = sqrt$2(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = sqrt$2(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = sqrt$2(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1) < 0) {
            out.x *= -1;
          }
          return out;
        }
        static getRotation(out, mat) {
          const trace = mat.m00 + mat.m05 + mat.m10;
          let S = 0;
          if (trace > 0) {
            S = sqrt$2(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 = sqrt$2(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 = sqrt$2(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 = sqrt$2(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;
        }
        static toRTS(m, q, v, s) {
          Mat4.toSRT(m, q, v, s);
        }
        static toSRT(m, q, v, s) {
          if (v) {
            Vec3.set(v, m.m12, m.m13, m.m14);
          }
          const sx = Vec3.set(v3_1$1, m.m00, m.m01, m.m02).length();
          const sy = Vec3.set(v3_1$1, m.m04, m.m05, m.m06).length();
          const sz = Vec3.set(v3_1$1, m.m08, m.m09, m.m10).length();
          if (s) {
            s.x = sx;
            s.y = sy;
            s.z = sz;
          }
          if (sx === 0 || sy === 0 || sz === 0) {
            if (q) {
              Quat.identity(q);
            }
            return;
          }
          m3_1.m00 = m.m00 / sx;
          m3_1.m01 = m.m01 / sx;
          m3_1.m02 = m.m02 / sx;
          m3_1.m03 = m.m04 / sy;
          m3_1.m04 = m.m05 / sy;
          m3_1.m05 = m.m06 / sy;
          m3_1.m06 = m.m08 / sz;
          m3_1.m07 = m.m09 / sz;
          m3_1.m08 = m.m10 / sz;
          const det = Mat3.determinant(m3_1);
          if (s) {
            if (det < 0) {
              s.x *= -1;
            }
          }
          if (q) {
            if (det < 0) {
              m3_1.m00 *= -1;
              m3_1.m01 *= -1;
              m3_1.m02 *= -1;
            }
            Quat.fromMat3(q, m3_1);
          }
        }
        static toEuler(m, v) {
          Mat3.set(m3_1, m.m00, m.m01, m.m02, m.m04, m.m05, m.m06, m.m08, m.m09, m.m10);
          return Mat3.toEuler(m3_1, v);
        }
        static fromRTS(out, q, v, s) {
          return Mat4.fromSRT(out, q, v, s);
        }
        static fromSRT(out, q, v, s) {
          const {
            x,
            y,
            z,
            w
          } = q;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const xy = x * y2;
          const xz = x * z2;
          const yy = y * y2;
          const yz = y * z2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const wz = w * z2;
          const sx = s.x;
          const sy = s.y;
          const 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;
        }
        static fromRTSOrigin(out, q, v, s, o) {
          return Mat4.fromSRTOrigin(out, q, v, s, o);
        }
        static fromSRTOrigin(out, q, v, s, o) {
          const x = q.x;
          const y = q.y;
          const z = q.z;
          const w = q.w;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const xy = x * y2;
          const xz = x * z2;
          const yy = y * y2;
          const yz = y * z2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const wz = w * z2;
          const sx = s.x;
          const sy = s.y;
          const sz = s.z;
          const ox = o.x;
          const oy = o.y;
          const 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;
        }
        static fromQuat(out, q) {
          const x = q.x;
          const y = q.y;
          const z = q.z;
          const w = q.w;
          const x2 = x + x;
          const y2 = y + y;
          const z2 = z + z;
          const xx = x * x2;
          const yx = y * x2;
          const yy = y * y2;
          const zx = z * x2;
          const zy = z * y2;
          const zz = z * z2;
          const wx = w * x2;
          const wy = w * y2;
          const 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;
        }
        static frustum(out, left, right, bottom, top, near, far) {
          const rl = 1 / (right - left);
          const tb = 1 / (top - bottom);
          const 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;
        }
        static perspective(out, fov, aspect, near, far, isFOVY = true, minClipZ = -1, projectionSignY = 1, orientation = 0) {
          const f = 1.0 / tan(fov / 2);
          const nf = 1 / (near - far);
          const x = isFOVY ? f / aspect : f;
          const y = (isFOVY ? f : f * aspect) * projectionSignY;
          const 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;
        }
        static ortho(out, left, right, bottom, top, near, far, minClipZ = -1, projectionSignY = 1, orientation = 0) {
          const lr = 1 / (left - right);
          const bt = 1 / (bottom - top) * projectionSignY;
          const nf = 1 / (near - far);
          const x = -2 * lr;
          const y = -2 * bt;
          const dx = (left + right) * lr;
          const dy = (top + bottom) * bt;
          const 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;
        }
        static lookAt(out, eye, center, up) {
          const eyex = eye.x;
          const eyey = eye.y;
          const eyez = eye.z;
          const upx = up.x;
          const upy = up.y;
          const upz = up.z;
          const centerx = center.x;
          const centery = center.y;
          const centerz = center.z;
          let z0 = eyex - centerx;
          let z1 = eyey - centery;
          let z2 = eyez - centerz;
          let len = 1 / sqrt$2(z0 * z0 + z1 * z1 + z2 * z2);
          z0 *= len;
          z1 *= len;
          z2 *= len;
          let x0 = upy * z2 - upz * z1;
          let x1 = upz * z0 - upx * z2;
          let x2 = upx * z1 - upy * z0;
          len = 1 / sqrt$2(x0 * x0 + x1 * x1 + x2 * x2);
          x0 *= len;
          x1 *= len;
          x2 *= len;
          const y0 = z1 * x2 - z2 * x1;
          const y1 = z2 * x0 - z0 * x2;
          const 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;
        }
        static inverseTranspose(out, a) {
          const a00 = a.m00;
          const a01 = a.m01;
          const a02 = a.m02;
          const a03 = a.m03;
          const a10 = a.m04;
          const a11 = a.m05;
          const a12 = a.m06;
          const a13 = a.m07;
          const a20 = a.m08;
          const a21 = a.m09;
          const a22 = a.m10;
          const a23 = a.m11;
          const a30 = a.m12;
          const a31 = a.m13;
          const a32 = a.m14;
          const a33 = a.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          let 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;
        }
        static toArray(out, m, 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;
        }
        static fromArray(out, arr, 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static 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;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          return abs$2(a.m00 - b.m00) <= epsilon * max$6(1.0, abs$2(a.m00), abs$2(b.m00)) && abs$2(a.m01 - b.m01) <= epsilon * max$6(1.0, abs$2(a.m01), abs$2(b.m01)) && abs$2(a.m02 - b.m02) <= epsilon * max$6(1.0, abs$2(a.m02), abs$2(b.m02)) && abs$2(a.m03 - b.m03) <= epsilon * max$6(1.0, abs$2(a.m03), abs$2(b.m03)) && abs$2(a.m04 - b.m04) <= epsilon * max$6(1.0, abs$2(a.m04), abs$2(b.m04)) && abs$2(a.m05 - b.m05) <= epsilon * max$6(1.0, abs$2(a.m05), abs$2(b.m05)) && abs$2(a.m06 - b.m06) <= epsilon * max$6(1.0, abs$2(a.m06), abs$2(b.m06)) && abs$2(a.m07 - b.m07) <= epsilon * max$6(1.0, abs$2(a.m07), abs$2(b.m07)) && abs$2(a.m08 - b.m08) <= epsilon * max$6(1.0, abs$2(a.m08), abs$2(b.m08)) && abs$2(a.m09 - b.m09) <= epsilon * max$6(1.0, abs$2(a.m09), abs$2(b.m09)) && abs$2(a.m10 - b.m10) <= epsilon * max$6(1.0, abs$2(a.m10), abs$2(b.m10)) && abs$2(a.m11 - b.m11) <= epsilon * max$6(1.0, abs$2(a.m11), abs$2(b.m11)) && abs$2(a.m12 - b.m12) <= epsilon * max$6(1.0, abs$2(a.m12), abs$2(b.m12)) && abs$2(a.m13 - b.m13) <= epsilon * max$6(1.0, abs$2(a.m13), abs$2(b.m13)) && abs$2(a.m14 - b.m14) <= epsilon * max$6(1.0, abs$2(a.m14), abs$2(b.m14)) && abs$2(a.m15 - b.m15) <= epsilon * max$6(1.0, abs$2(a.m15), abs$2(b.m15));
        }
        constructor(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) {
          super();
          const self = this;
          if (typeof m00 === 'object') {
            self.m00 = m00.m00;
            this.m01 = m00.m01;
            this.m02 = m00.m02;
            this.m03 = m00.m03;
            self.m04 = m00.m04;
            this.m05 = m00.m05;
            this.m06 = m00.m06;
            this.m07 = m00.m07;
            self.m08 = m00.m08;
            this.m09 = m00.m09;
            this.m10 = m00.m10;
            this.m11 = m00.m11;
            self.m12 = m00.m12;
            this.m13 = m00.m13;
            this.m14 = m00.m14;
            this.m15 = m00.m15;
          } else {
            self.m00 = m00;
            this.m01 = m01;
            this.m02 = m02;
            this.m03 = m03;
            self.m04 = m04;
            this.m05 = m05;
            this.m06 = m06;
            this.m07 = m07;
            self.m08 = m08;
            this.m09 = m09;
            this.m10 = m10;
            this.m11 = m11;
            self.m12 = m12;
            this.m13 = m13;
            this.m14 = m14;
            this.m15 = m15;
          }
        }
        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);
        }
        set(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) {
          const self = this;
          if (typeof m00 === 'object') {
            self.m01 = m00.m01;
            self.m02 = m00.m02;
            self.m03 = m00.m03;
            self.m04 = m00.m04;
            self.m05 = m00.m05;
            self.m06 = m00.m06;
            self.m07 = m00.m07;
            self.m08 = m00.m08;
            self.m09 = m00.m09;
            self.m10 = m00.m10;
            self.m11 = m00.m11;
            self.m12 = m00.m12;
            self.m13 = m00.m13;
            self.m14 = m00.m14;
            self.m15 = m00.m15;
            self.m00 = m00.m00;
          } else {
            self.m01 = m01;
            self.m02 = m02;
            self.m03 = m03;
            self.m04 = m04;
            self.m05 = m05;
            self.m06 = m06;
            self.m07 = m07;
            self.m08 = m08;
            self.m09 = m09;
            self.m10 = m10;
            self.m11 = m11;
            self.m12 = m12;
            self.m13 = m13;
            self.m14 = m14;
            self.m15 = m15;
            self.m00 = m00;
          }
          return self;
        }
        equals(other, epsilon = EPSILON$2) {
          const inf = Infinity;
          const self = this;
          const m00 = self.m00;
          const m01 = self.m01;
          const m02 = self.m02;
          const m03 = self.m03;
          const m04 = self.m04;
          const m05 = self.m05;
          const m06 = self.m06;
          const m07 = self.m07;
          const m08 = self.m08;
          const m09 = self.m09;
          const m10 = self.m10;
          const m11 = self.m11;
          const m12 = self.m12;
          const m13 = self.m13;
          const m14 = self.m14;
          const m15 = self.m15;
          const hasInf = abs$2(m00) === inf || abs$2(m01) === inf || abs$2(m02) === inf || abs$2(m03) === inf || abs$2(m04) === inf || abs$2(m05) === inf || abs$2(m06) === inf || abs$2(m07) === inf || abs$2(m08) === inf || abs$2(m09) === inf || abs$2(m10) === inf || abs$2(m11) === inf || abs$2(m12) === inf || abs$2(m13) === inf || abs$2(m14) === inf || abs$2(m15) === inf;
          return !hasInf && abs$2(m00 - other.m00) <= epsilon * max$6(1.0, abs$2(m00), abs$2(other.m00)) && abs$2(m01 - other.m01) <= epsilon * max$6(1.0, abs$2(m01), abs$2(other.m01)) && abs$2(m02 - other.m02) <= epsilon * max$6(1.0, abs$2(m02), abs$2(other.m02)) && abs$2(m03 - other.m03) <= epsilon * max$6(1.0, abs$2(m03), abs$2(other.m03)) && abs$2(m04 - other.m04) <= epsilon * max$6(1.0, abs$2(m04), abs$2(other.m04)) && abs$2(m05 - other.m05) <= epsilon * max$6(1.0, abs$2(m05), abs$2(other.m05)) && abs$2(m06 - other.m06) <= epsilon * max$6(1.0, abs$2(m06), abs$2(other.m06)) && abs$2(m07 - other.m07) <= epsilon * max$6(1.0, abs$2(m07), abs$2(other.m07)) && abs$2(m08 - other.m08) <= epsilon * max$6(1.0, abs$2(m08), abs$2(other.m08)) && abs$2(m09 - other.m09) <= epsilon * max$6(1.0, abs$2(m09), abs$2(other.m09)) && abs$2(m10 - other.m10) <= epsilon * max$6(1.0, abs$2(m10), abs$2(other.m10)) && abs$2(m11 - other.m11) <= epsilon * max$6(1.0, abs$2(m11), abs$2(other.m11)) && abs$2(m12 - other.m12) <= epsilon * max$6(1.0, abs$2(m12), abs$2(other.m12)) && abs$2(m13 - other.m13) <= epsilon * max$6(1.0, abs$2(m13), abs$2(other.m13)) && abs$2(m14 - other.m14) <= epsilon * max$6(1.0, abs$2(m14), abs$2(other.m14)) && abs$2(m15 - other.m15) <= epsilon * max$6(1.0, abs$2(m15), abs$2(other.m15));
        }
        strictEquals(other) {
          const self = this;
          return self.m00 === other.m00 && self.m01 === other.m01 && self.m02 === other.m02 && self.m03 === other.m03 && self.m04 === other.m04 && self.m05 === other.m05 && self.m06 === other.m06 && self.m07 === other.m07 && self.m08 === other.m08 && self.m09 === other.m09 && self.m10 === other.m10 && self.m11 === other.m11 && self.m12 === other.m12 && self.m13 === other.m13 && self.m14 === other.m14 && self.m15 === other.m15;
        }
        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` + ']';
        }
        identity() {
          return Mat4.identity(this);
        }
        zero() {
          return Mat4.zero(this);
        }
        transpose() {
          const self = this;
          const a01 = self.m01;
          const a02 = self.m02;
          const a03 = self.m03;
          const a12 = self.m06;
          const a13 = self.m07;
          const a23 = self.m11;
          self.m01 = self.m04;
          self.m02 = self.m08;
          self.m03 = self.m12;
          self.m04 = a01;
          self.m06 = self.m09;
          self.m07 = self.m13;
          self.m08 = a02;
          self.m09 = a12;
          self.m11 = self.m14;
          self.m12 = a03;
          self.m13 = a13;
          self.m14 = a23;
          return self;
        }
        invert() {
          const self = this;
          const a00 = self.m00;
          const a01 = self.m01;
          const a02 = self.m02;
          const a03 = self.m03;
          const a10 = self.m04;
          const a11 = self.m05;
          const a12 = self.m06;
          const a13 = self.m07;
          const a20 = self.m08;
          const a21 = self.m09;
          const a22 = self.m10;
          const a23 = self.m11;
          const a30 = self.m12;
          const a31 = self.m13;
          const a32 = self.m14;
          const a33 = self.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            self.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
            return self;
          }
          det = 1.0 / det;
          self.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          self.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          self.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          self.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
          self.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          self.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          self.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          self.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
          self.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          self.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          self.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          self.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
          self.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
          self.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
          self.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
          self.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
          return self;
        }
        determinant() {
          const self = this;
          const a00 = self.m00;
          const a01 = self.m01;
          const a02 = self.m02;
          const a03 = self.m03;
          const a10 = self.m04;
          const a11 = self.m05;
          const a12 = self.m06;
          const a13 = self.m07;
          const a20 = self.m08;
          const a21 = self.m09;
          const a22 = self.m10;
          const a23 = self.m11;
          const a30 = self.m12;
          const a31 = self.m13;
          const a32 = self.m14;
          const a33 = self.m15;
          const b00 = a00 * a11 - a01 * a10;
          const b01 = a00 * a12 - a02 * a10;
          const b02 = a00 * a13 - a03 * a10;
          const b03 = a01 * a12 - a02 * a11;
          const b04 = a01 * a13 - a03 * a11;
          const b05 = a02 * a13 - a03 * a12;
          const b06 = a20 * a31 - a21 * a30;
          const b07 = a20 * a32 - a22 * a30;
          const b08 = a20 * a33 - a23 * a30;
          const b09 = a21 * a32 - a22 * a31;
          const b10 = a21 * a33 - a23 * a31;
          const b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        }
        add(mat) {
          const self = this;
          self.m00 += mat.m00;
          self.m01 += mat.m01;
          self.m02 += mat.m02;
          self.m03 += mat.m03;
          self.m04 += mat.m04;
          self.m05 += mat.m05;
          self.m06 += mat.m06;
          self.m07 += mat.m07;
          self.m08 += mat.m08;
          self.m09 += mat.m09;
          self.m10 += mat.m10;
          self.m11 += mat.m11;
          self.m12 += mat.m12;
          self.m13 += mat.m13;
          self.m14 += mat.m14;
          self.m15 += mat.m15;
          return self;
        }
        subtract(mat) {
          const self = this;
          self.m00 -= mat.m00;
          self.m01 -= mat.m01;
          self.m02 -= mat.m02;
          self.m03 -= mat.m03;
          self.m04 -= mat.m04;
          self.m05 -= mat.m05;
          self.m06 -= mat.m06;
          self.m07 -= mat.m07;
          self.m08 -= mat.m08;
          self.m09 -= mat.m09;
          self.m10 -= mat.m10;
          self.m11 -= mat.m11;
          self.m12 -= mat.m12;
          self.m13 -= mat.m13;
          self.m14 -= mat.m14;
          self.m15 -= mat.m15;
          return self;
        }
        multiply(mat) {
          return Mat4.multiply(this, this, mat);
        }
        multiplyScalar(scalar) {
          const self = this;
          self.m00 *= scalar;
          self.m01 *= scalar;
          self.m02 *= scalar;
          self.m03 *= scalar;
          self.m04 *= scalar;
          self.m05 *= scalar;
          self.m06 *= scalar;
          self.m07 *= scalar;
          self.m08 *= scalar;
          self.m09 *= scalar;
          self.m10 *= scalar;
          self.m11 *= scalar;
          self.m12 *= scalar;
          self.m13 *= scalar;
          self.m14 *= scalar;
          self.m15 *= scalar;
          return self;
        }
        translate(vec) {
          this.m12 += vec.x;
          this.m13 += vec.y;
          this.m14 += vec.z;
          return this;
        }
        transform(vec) {
          const {
            x,
            y,
            z
          } = vec;
          const self = this;
          const a00 = self.m00;
          const a01 = self.m01;
          const a02 = self.m02;
          const a03 = self.m03;
          const a10 = self.m04;
          const a11 = self.m05;
          const a12 = self.m06;
          const a13 = self.m07;
          const a20 = self.m08;
          const a21 = self.m09;
          const a22 = self.m10;
          const a23 = self.m11;
          self.m12 = a00 * x + a10 * y + a20 * z + self.m12;
          self.m13 = a01 * x + a11 * y + a21 * z + self.m13;
          self.m14 = a02 * x + a12 * y + a22 * z + self.m14;
          self.m15 = a03 * x + a13 * y + a23 * z + self.m15;
          return self;
        }
        scale(vec) {
          const {
            x,
            y,
            z
          } = vec;
          const self = this;
          self.m00 *= x;
          self.m01 *= x;
          self.m02 *= x;
          self.m03 *= x;
          self.m04 *= y;
          self.m05 *= y;
          self.m06 *= y;
          self.m07 *= y;
          self.m08 *= z;
          self.m09 *= z;
          self.m10 *= z;
          self.m11 *= z;
          return self;
        }
        rotate(rad, axis) {
          let x = axis.x;
          let y = axis.y;
          let z = axis.z;
          let len = sqrt$2(x * x + y * y + z * z);
          if (abs$2(len) < EPSILON$2) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          const s = sin$3(rad);
          const c = cos$4(rad);
          const t = 1 - c;
          const self = this;
          const a00 = self.m00;
          const a01 = self.m01;
          const a02 = self.m02;
          const a03 = self.m03;
          const a10 = self.m04;
          const a11 = self.m05;
          const a12 = self.m06;
          const a13 = self.m07;
          const a20 = self.m08;
          const a21 = self.m09;
          const a22 = self.m10;
          const a23 = self.m11;
          const b00 = x * x * t + c;
          const b01 = y * x * t + z * s;
          const b02 = z * x * t - y * s;
          const b10 = x * y * t - z * s;
          const b11 = y * y * t + c;
          const b12 = z * y * t + x * s;
          const b20 = x * z * t + y * s;
          const b21 = y * z * t - x * s;
          const b22 = z * z * t + c;
          self.m00 = a00 * b00 + a10 * b01 + a20 * b02;
          self.m01 = a01 * b00 + a11 * b01 + a21 * b02;
          self.m02 = a02 * b00 + a12 * b01 + a22 * b02;
          self.m03 = a03 * b00 + a13 * b01 + a23 * b02;
          self.m04 = a00 * b10 + a10 * b11 + a20 * b12;
          self.m05 = a01 * b10 + a11 * b11 + a21 * b12;
          self.m06 = a02 * b10 + a12 * b11 + a22 * b12;
          self.m07 = a03 * b10 + a13 * b11 + a23 * b12;
          self.m08 = a00 * b20 + a10 * b21 + a20 * b22;
          self.m09 = a01 * b20 + a11 * b21 + a21 * b22;
          self.m10 = a02 * b20 + a12 * b21 + a22 * b22;
          self.m11 = a03 * b20 + a13 * b21 + a23 * b22;
          return self;
        }
        getTranslation(out) {
          out.x = this.m12;
          out.y = this.m13;
          out.z = this.m14;
          return out;
        }
        getScale(out) {
          const self = this;
          const m00 = m3_1.m00 = self.m00;
          const m01 = m3_1.m01 = self.m01;
          const m02 = m3_1.m02 = self.m02;
          const m04 = m3_1.m03 = self.m04;
          const m05 = m3_1.m04 = self.m05;
          const m06 = m3_1.m05 = self.m06;
          const m08 = m3_1.m06 = self.m08;
          const m09 = m3_1.m07 = self.m09;
          const m10 = m3_1.m08 = self.m10;
          out.x = sqrt$2(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = sqrt$2(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = sqrt$2(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1) < 0) {
            out.x *= -1;
          }
          return out;
        }
        getRotation(out) {
          const self = this;
          const sx = Vec3.set(v3_1$1, self.m00, self.m01, self.m02).length();
          const sy = Vec3.set(v3_1$1, self.m04, self.m05, self.m06).length();
          const sz = Vec3.set(v3_1$1, self.m08, self.m09, self.m10).length();
          m3_1.m00 = self.m00 / sx;
          m3_1.m01 = self.m01 / sx;
          m3_1.m02 = self.m02 / sx;
          m3_1.m03 = self.m04 / sy;
          m3_1.m04 = self.m05 / sy;
          m3_1.m05 = self.m06 / sy;
          m3_1.m06 = self.m08 / sz;
          m3_1.m07 = self.m09 / sz;
          m3_1.m08 = self.m10 / sz;
          const det = Mat3.determinant(m3_1);
          if (det < 0) {
            m3_1.m00 *= -1;
            m3_1.m01 *= -1;
            m3_1.m02 *= -1;
          }
          return Quat.fromMat3(out, m3_1);
        }
        fromRTS(q, v, s) {
          return Mat4.fromSRT(this, q, v, s);
        }
        fromSRT(q, v, s) {
          return Mat4.fromSRT(this, q, v, s);
        }
        fromQuat(q) {
          return Mat4.fromQuat(this, q);
        }
      } exports("Mat4", Mat4);
      _class$2t = Mat4;
      Mat4.IDENTITY = Object.freeze(new _class$2t());
      const v3_1$1 = new Vec3();
      const m3_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$2s;
      const abs$1 = Math.abs;
      const max$5 = Math.max;
      const min$4 = Math.min;
      const PI$2 = Math.PI;
      const acos$2 = Math.acos;
      const sin$2 = Math.sin;
      const cos$3 = Math.cos;
      const sqrt$1 = Math.sqrt;
      const atan2$1 = Math.atan2;
      const ceil$2 = Math.ceil;
      const floor = Math.floor;
      const round = Math.round;
      class Vec2 extends ValueType {
        static clone(a) {
          return new Vec2(a.x, a.y);
        }
        static copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          return out;
        }
        static set(out, x, y) {
          out.x = x;
          out.y = y;
          return out;
        }
        static add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          return out;
        }
        static subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          return out;
        }
        static multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          return out;
        }
        static divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          return out;
        }
        static ceil(out, a) {
          out.x = ceil$2(a.x);
          out.y = ceil$2(a.y);
          return out;
        }
        static floor(out, a) {
          out.x = floor(a.x);
          out.y = floor(a.y);
          return out;
        }
        static min(out, a, b) {
          out.x = min$4(a.x, b.x);
          out.y = min$4(a.y, b.y);
          return out;
        }
        static max(out, a, b) {
          out.x = max$5(a.x, b.x);
          out.y = max$5(a.y, b.y);
          return out;
        }
        static round(out, a) {
          out.x = round(a.x);
          out.y = round(a.y);
          return out;
        }
        static multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          return out;
        }
        static scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          return out;
        }
        static distance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          return sqrt$1(x * x + y * y);
        }
        static squaredDistance(a, b) {
          const x = b.x - a.x;
          const y = b.y - a.y;
          return x * x + y * y;
        }
        static len(a) {
          const x = a.x;
          const y = a.y;
          return sqrt$1(x * x + y * y);
        }
        static lengthSqr(a) {
          const x = a.x;
          const y = a.y;
          return x * x + y * y;
        }
        static negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          return out;
        }
        static inverse(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          return out;
        }
        static inverseSafe(out, a) {
          const x = a.x;
          const y = a.y;
          if (abs$1(x) < EPSILON$2) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (abs$1(y) < EPSILON$2) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          return out;
        }
        static normalize(out, a) {
          const x = a.x;
          const y = a.y;
          let len = x * x + y * y;
          if (len > 0) {
            len = 1 / sqrt$1(len);
            out.x = x * len;
            out.y = y * len;
          } else {
            out.x = 0;
            out.y = 0;
          }
          return out;
        }
        static dot(a, b) {
          return a.x * b.x + a.y * b.y;
        }
        static 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;
          }
        }
        static lerp(out, a, b, t) {
          const x = a.x;
          const y = a.y;
          out.x = x + t * (b.x - x);
          out.y = y + t * (b.y - y);
          return out;
        }
        static random(out, scale) {
          scale = scale || 1.0;
          const r = random() * 2.0 * PI$2;
          out.x = cos$3(r) * scale;
          out.y = sin$2(r) * scale;
          return out;
        }
        static transformMat3(out, a, m) {
          const x = a.x;
          const 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;
        }
        static transformMat4(out, a, m) {
          const x = a.x;
          const 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;
        }
        static str(a) {
          return `Vec2(${a.x}, ${a.y})`;
        }
        static toArray(out, v, ofs = 0) {
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          return out;
        }
        static fromArray(out, arr, ofs = 0) {
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          return out;
        }
        static strictEquals(a, b) {
          return a.x === b.x && a.y === b.y;
        }
        static equals(a, b, epsilon = EPSILON$2) {
          return abs$1(a.x - b.x) <= epsilon * max$5(1.0, abs$1(a.x), abs$1(b.x)) && abs$1(a.y - b.y) <= epsilon * max$5(1.0, abs$1(a.y), abs$1(b.y));
        }
        static angle(a, b) {
          const magSqr1 = a.x * a.x + a.y * a.y;
          const magSqr2 = b.x * b.x + b.y * b.y;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          const dot = a.x * b.x + a.y * b.y;
          let cosine = dot / sqrt$1(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return acos$2(cosine);
        }
        constructor(x, y) {
          super();
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
          } else {
            this.x = x || 0;
            this.y = y || 0;
          }
        }
        clone() {
          return new Vec2(this.x, this.y);
        }
        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;
        }
        equals(other, epsilon = EPSILON$2) {
          return Vec2.equals(this, other, epsilon);
        }
        equals2f(x, y, epsilon = EPSILON$2) {
          return abs$1(this.x - x) <= epsilon * max$5(1.0, abs$1(this.x), abs$1(x)) && abs$1(this.y - y) <= epsilon * max$5(1.0, abs$1(this.y), abs$1(y));
        }
        strictEquals(other) {
          return other && this.x === other.x && this.y === other.y;
        }
        strictEquals2f(x, y) {
          return this.x === x && this.y === y;
        }
        toString() {
          return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`;
        }
        lerp(to, ratio) {
          const x = this.x;
          const y = this.y;
          this.x = x + ratio * (to.x - x);
          this.y = y + ratio * (to.y - y);
          return this;
        }
        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;
        }
        add(other) {
          this.x += other.x;
          this.y += other.y;
          return this;
        }
        add2f(x, y) {
          this.x += x;
          this.y += y;
          return this;
        }
        subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          return this;
        }
        subtract2f(x, y) {
          this.x -= x;
          this.y -= y;
          return this;
        }
        multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            warnID(16359);
          }
          this.x *= scalar;
          this.y *= scalar;
          return this;
        }
        multiply(other) {
          if (typeof other !== 'object') {
            warnID(16360);
          }
          this.x *= other.x;
          this.y *= other.y;
          return this;
        }
        multiply2f(x, y) {
          this.x *= x;
          this.y *= y;
          return this;
        }
        divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          return this;
        }
        divide2f(x, y) {
          this.x /= x;
          this.y /= y;
          return this;
        }
        negative() {
          this.x = -this.x;
          this.y = -this.y;
          return this;
        }
        dot(other) {
          return this.x * other.x + this.y * other.y;
        }
        cross(other) {
          return this.x * other.y - this.y * other.x;
        }
        length() {
          return sqrt$1(this.x * this.x + this.y * this.y);
        }
        lengthSqr() {
          return this.x * this.x + this.y * this.y;
        }
        normalize() {
          const self = this;
          const x = self.x;
          const y = self.y;
          let len = x * x + y * y;
          if (len > 0) {
            len = 1 / sqrt$1(len);
            self.x *= len;
            self.y *= len;
          }
          return self;
        }
        angle(other) {
          const magSqr1 = this.lengthSqr();
          const magSqr2 = other.lengthSqr();
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          const dot = this.dot(other);
          let cosine = dot / sqrt$1(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return acos$2(cosine);
        }
        signAngle(other) {
          const cross = this.cross(other);
          const dot = this.dot(other);
          return atan2$1(cross, dot);
        }
        rotate(radians) {
          const x = this.x;
          const y = this.y;
          const s = sin$2(radians);
          const c = cos$3(radians);
          this.x = c * x - s * y;
          this.y = s * x + c * y;
          return this;
        }
        project(other) {
          const scalar = this.dot(other) / other.dot(other);
          this.x = other.x * scalar;
          this.y = other.y * scalar;
          return this;
        }
        transformMat4(matrix) {
          const x = this.x;
          const 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;
        }
        toVec3() {
          return new Vec3(this.x, this.y, 0);
        }
      } exports("Vec2", Vec2);
      _class$2s = Vec2;
      Vec2.ZERO = Object.freeze(new _class$2s(0, 0));
      Vec2.ONE = Object.freeze(new _class$2s(1, 1));
      Vec2.NEG_ONE = Object.freeze(new _class$2s(-1, -1));
      Vec2.UNIT_X = Object.freeze(new _class$2s(1, 0));
      Vec2.UNIT_Y = Object.freeze(new _class$2s(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;

      replaceProperty(Vec2, 'Vec2', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec2,
        targetName: 'Vec2'
      }]);
      replaceProperty(Vec2.prototype, 'Vec2', [{
        name: 'mag',
        newName: 'length',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }]);
      replaceProperty(Vec3, 'Vec3', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec3,
        targetName: 'Vec3'
      }]);
      replaceProperty(Vec3.prototype, 'Vec3', [{
        name: 'mag',
        newName: 'length',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }]);
      replaceProperty(Vec4, 'Vec4', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec4,
        targetName: 'Vec4'
      }]);
      replaceProperty(Vec4.prototype, 'Vec4', [{
        name: 'mag',
        newName: 'length',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }]);
      replaceProperty(Quat, 'Quat', [{
        name: 'mag',
        newName: 'len',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Quat,
        targetName: 'Quat'
      }]);
      replaceProperty(Quat.prototype, 'Quat', [{
        name: 'scale',
        newName: 'multiplyScalar',
        target: Quat.prototype,
        targetName: 'Quat'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Quat.prototype,
        targetName: 'Quat'
      }]);
      replaceProperty(Color$1, 'Color', [{
        name: 'sub',
        newName: 'subtract',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'div',
        newName: 'divide',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'fromHex',
        newName: 'fromHEX',
        customFunction(...args) {
          const arg1 = args[1].toString(16);
          return legacyCC.Color.fromHEX(args[0], arg1);
        }
      }]);
      replaceProperty(Mat3, 'Mat3', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'transfrom',
        newName: 'transform',
        target: Mat3,
        targetName: 'Mat3'
      }]);
      replaceProperty(Mat3.prototype, 'Mat3', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'mulScalar',
        newName: 'multiplyScalar',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }]);
      replaceProperty(Mat4, 'Mat4', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat4,
        targetName: 'Mat4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat4,
        targetName: 'Mat4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat4,
        targetName: 'Mat4'
      }]);
      replaceProperty(Mat4.prototype, 'Mat4', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'mulScalar',
        newName: 'multiplyScalar',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }]);

      {
        const defineAttr = (proto, name, offset) => {
          Object.defineProperty(proto, name, {
            configurable: true,
            enumerable: true,
            get() {
              return this._data()[offset];
            },
            set(v) {
              this._data()[offset] = v;
            }
          });
        };
        const extendType = (proto, parentProto, typ) => {
          proto._data = function _data() {
            if (!this.__data) {
              this.__data = new Float32Array(this.underlyingData());
            }
            return this.__data;
          };
          Object.setPrototypeOf(proto, parentProto);
          Object.defineProperty(proto, 'type', {
            configurable: true,
            enumerable: true,
            writable: false,
            value: typ
          });
        };
        const inheritCCClass = (ctor, parentCtor) => {
          for (const attrName of ['__cid__', '__classname__']) {
            Object.defineProperty(ctor.prototype, attrName, {
              value: parentCtor.prototype[attrName],
              writable: false,
              enumerable: false,
              configurable: true
            });
          }
          for (const staticKey of ['__attrs__', '__props__', '__values__']) {
            ctor[staticKey] = parentCtor[staticKey];
          }
        };
        extendType(jsb.Mat4.prototype, Mat4.prototype, 5);
        for (let i = 0; i < 16; i++) {
          const numb = `0${i}`;
          defineAttr(jsb.Mat4.prototype, `m${numb.substring(numb.length - 2)}`, i);
        }
        for (let i = 0; i < 9; i++) {
          const numb = `0${i}`;
          defineAttr(jsb.Mat3.prototype, `m${numb.substring(numb.length - 2)}`, i);
        }
        extendType(jsb.Mat3.prototype, Mat3.prototype, 4);
        defineAttr(jsb.Vec2.prototype, 'x', 0);
        defineAttr(jsb.Vec2.prototype, 'y', 1);
        extendType(jsb.Vec2.prototype, Vec2.prototype, 0);
        defineAttr(jsb.Vec3.prototype, 'x', 0);
        defineAttr(jsb.Vec3.prototype, 'y', 1);
        defineAttr(jsb.Vec3.prototype, 'z', 2);
        extendType(jsb.Vec3.prototype, Vec3.prototype, 1);
        defineAttr(jsb.Vec4.prototype, 'x', 0);
        defineAttr(jsb.Vec4.prototype, 'y', 1);
        defineAttr(jsb.Vec4.prototype, 'z', 2);
        defineAttr(jsb.Vec4.prototype, 'w', 3);
        extendType(jsb.Vec4.prototype, Vec4.prototype, 2);
        defineAttr(jsb.Quat.prototype, 'x', 0);
        defineAttr(jsb.Quat.prototype, 'y', 1);
        defineAttr(jsb.Quat.prototype, 'z', 2);
        defineAttr(jsb.Quat.prototype, 'w', 3);
        extendType(jsb.Quat.prototype, Quat.prototype, 3);
        Object.setPrototypeOf(jsb.Color.prototype, Color$1.prototype);
        Object.defineProperty(jsb.Color.prototype, 'type', {
          configurable: true,
          enumerable: true,
          writable: false,
          value: 8
        });
        inheritCCClass(jsb.Vec4, Vec4);
        inheritCCClass(jsb.Vec3, Vec3);
        inheritCCClass(jsb.Vec2, Vec2);
        inheritCCClass(jsb.Mat4, Mat4);
        inheritCCClass(jsb.Mat3, Mat3);
        inheritCCClass(jsb.Color, Color$1);
        inheritCCClass(jsb.Quat, Quat);
      }

      class AffineTransform {
        static identity() {
          return new AffineTransform();
        }
        static clone(affineTransform) {
          return new AffineTransform(affineTransform.a, affineTransform.b, affineTransform.c, affineTransform.d, affineTransform.tx, affineTransform.ty);
        }
        static concat(out, t1, t2) {
          const a = t1.a;
          const b = t1.b;
          const c = t1.c;
          const d = t1.d;
          const tx = t1.tx;
          const 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;
        }
        static invert(out, t) {
          const 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);
        }
        static 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;
        }
        static transformVec2(out, point, transOrY, t) {
          let x;
          let 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;
        }
        static transformSize(out, size, t) {
          out.width = t.a * size.width + t.c * size.height;
          out.height = t.b * size.width + t.d * size.height;
        }
        static transformRect(out, rect, t) {
          const or = rect.x + rect.width;
          const ot = rect.y + rect.height;
          const lbx = t.a * rect.x + t.c * rect.y + t.tx;
          const lby = t.b * rect.x + t.d * rect.y + t.ty;
          const rbx = t.a * or + t.c * rect.y + t.tx;
          const rby = t.b * or + t.d * rect.y + t.ty;
          const ltx = t.a * rect.x + t.c * ot + t.tx;
          const lty = t.b * rect.x + t.d * ot + t.ty;
          const rtx = t.a * or + t.c * ot + t.tx;
          const rty = t.b * or + t.d * ot + t.ty;
          const minX = Math.min(lbx, rbx, ltx, rtx);
          const maxX = Math.max(lbx, rbx, ltx, rtx);
          const minY = Math.min(lby, rby, lty, rty);
          const maxY = Math.max(lby, rby, lty, rty);
          out.x = minX;
          out.y = minY;
          out.width = maxX - minX;
          out.height = maxY - minY;
        }
        static transformObb(out_bl, out_tl, out_tr, out_br, rect, anAffineTransform, flipY = true) {
          const tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx;
          const ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty;
          const xa = anAffineTransform.a * rect.width;
          const xb = anAffineTransform.b * rect.width;
          const yc = anAffineTransform.c * rect.height;
          const 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;
          }
        }
        constructor(a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0) {
          this.a = a;
          this.b = b;
          this.c = c;
          this.d = d;
          this.tx = tx;
          this.ty = ty;
        }
      } exports("AffineTransform", AffineTransform);
      legacyCC.AffineTransform = AffineTransform;

      var _class$2r;
      let Size$1 = class Size extends ValueType {
        static 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;
        }
        static equals(a, b) {
          return a.width === b.width && a.height === b.height;
        }
        set x(val) {
          this.width = val;
        }
        get x() {
          return this.width;
        }
        set y(val) {
          this.height = val;
        }
        get y() {
          return this.height;
        }
        constructor(width, height) {
          super();
          if (typeof width === 'object') {
            this.width = width.width;
            this.height = width.height;
          } else {
            this.width = width || 0;
            this.height = height || 0;
          }
        }
        clone() {
          return new Size(this.width, this.height);
        }
        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;
        }
        equals(other) {
          return this.width === other.width && this.height === other.height;
        }
        lerp(to, ratio) {
          this.width += (to.width - this.width) * ratio;
          this.height += (to.height - this.height) * ratio;
          return this;
        }
        toString() {
          return `(${this.width.toFixed(2)}, ${this.height.toFixed(2)})`;
        }
      }; exports("Size", Size$1);
      _class$2r = Size$1;
      Size$1.ZERO = Object.freeze(new _class$2r(0, 0));
      Size$1.ONE = Object.freeze(new _class$2r(1, 1));
      CCClass.fastDefine('cc.Size', Size$1, {
        width: 0,
        height: 0
      });
      function size(width = 0, height = 0) {
        return new Size$1(width, height);
      }
      legacyCC.size = size;
      legacyCC.Size = Size$1;

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

      const MATH_FLOAT_ARRAY = exports("MATH_FLOAT_ARRAY", Float32Array );
      class MathBase extends ValueType {
        static createFloatArray(size) {
          return new MATH_FLOAT_ARRAY(size);
        }
        get array() {
          return this._array;
        }
      } exports("MathBase", MathBase);

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

      const X = new Vec3();
      const Y = new Vec3();
      const Z = new Vec3();
      const d = new Vec3();
      const min$2 = new Vec3();
      const max$3 = new Vec3();
      const u = new Array(3);
      const e = new Array(3);
      function point_plane(point, plane_) {
        return Vec3.dot(plane_.n, point) - plane_.d;
      }
      function pt_point_plane(out, point, plane_) {
        const 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 (let i = 0; i < 3; i++) {
          let 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);
        const dir = X.clone();
        const dirSquaredLength = Vec3.lengthSqr(dir);
        if (dirSquaredLength === 0) {
          Vec3.copy(out, linePointA);
        } else {
          Vec3.subtract(X, point, linePointA);
          const 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_aabb: pt_point_aabb,
        pt_point_line: pt_point_line,
        pt_point_obb: pt_point_obb,
        pt_point_plane: pt_point_plane
      });

      class Line {
        static create(sx, sy, sz, ex, ey, ez) {
          return new Line(sx, sy, sz, ex, ey, ez);
        }
        static clone(a) {
          return new Line(a.s.x, a.s.y, a.s.z, a.e.x, a.e.y, a.e.z);
        }
        static copy(out, a) {
          Vec3.copy(out.s, a.s);
          Vec3.copy(out.e, a.e);
          return out;
        }
        static fromPoints(out, start, end) {
          Vec3.copy(out.s, start);
          Vec3.copy(out.e, end);
          return out;
        }
        static 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;
        }
        static len(a) {
          return Vec3.distance(a.s, a.e);
        }
        get type() {
          return this._type;
        }
        constructor(sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) {
          this.s = void 0;
          this.e = void 0;
          this._type = void 0;
          this._type = 2;
          this.s = new Vec3(sx, sy, sz);
          this.e = new Vec3(ex, ey, ez);
        }
        length() {
          return Vec3.distance(this.s, this.e);
        }
      }

      class Ray {
        static create(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = 1) {
          return new Ray(ox, oy, oz, dx, dy, dz);
        }
        static clone(a) {
          return new Ray(a.o.x, a.o.y, a.o.z, a.d.x, a.d.y, a.d.z);
        }
        static copy(out, a) {
          Vec3.copy(out.o, a.o);
          Vec3.copy(out.d, a.d);
          return out;
        }
        static fromPoints(out, origin, target) {
          Vec3.copy(out.o, origin);
          Vec3.normalize(out.d, Vec3.subtract(out.d, target, origin));
          return out;
        }
        static 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;
        }
        get type() {
          return this._type;
        }
        constructor(ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) {
          this._type = 1;
          this.o = new Vec3(ox, oy, oz);
          this.d = new Vec3(dx, dy, dz);
        }
        computeHit(out, distance) {
          Vec3.normalize(out, this.d);
          Vec3.scaleAndAdd(out, this.o, out, distance);
        }
      }

      const _v3_tmp$2 = new Vec3();
      const _offset = new Vec3();
      const _min = new Vec3();
      const _max = new Vec3();
      function maxComponent(v) {
        return Math.max(Math.max(v.x, v.y), v.z);
      }
      class Sphere {
        static create(cx, cy, cz, r) {
          return new Sphere(cx, cy, cz, r);
        }
        static clone(p) {
          return new Sphere(p.center.x, p.center.y, p.center.z, p.radius);
        }
        static copy(out, p) {
          Vec3.copy(out.center, p.center);
          out.radius = p.radius;
          return out;
        }
        static 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;
        }
        static set(out, cx, cy, cz, r) {
          out.center.x = cx;
          out.center.y = cy;
          out.center.z = cz;
          out.radius = r;
          return out;
        }
        get center() {
          return this._center;
        }
        set center(val) {
          this._center = val;
        }
        get radius() {
          return this._radius;
        }
        set radius(val) {
          this._radius = val;
        }
        get type() {
          return this._type;
        }
        constructor(cx = 0, cy = 0, cz = 0, r = 1) {
          this._type = 4;
          this._center = new Vec3(cx, cy, cz);
          this._radius = r;
        }
        destroy() {}
        clone() {
          return Sphere.clone(this);
        }
        copy(a) {
          return Sphere.copy(this, a);
        }
        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);
        }
        transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          out.radius = this.radius * maxComponent(scale);
        }
        translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
        }
        setScale(scale, out) {
          out.radius = this.radius * maxComponent(scale);
        }
        mergePoint(point) {
          if (this.radius < 0.0) {
            this.center.set(point);
            this.radius = 0.0;
          }
          Vec3.subtract(_offset, point, this.center);
          const dist = _offset.length();
          if (dist > this.radius) {
            const half = (dist - this.radius) * 0.5;
            this.radius += half;
            Vec3.multiplyScalar(_offset, _offset, half / dist);
            Vec3.add(this.center, this.center, _offset);
          }
        }
        mergePoints(points) {
          const length = points.length;
          if (length < 1) return;
          this.radius = -1.0;
          for (let i = 0; i < length; i++) {
            this.mergePoint(points[i]);
          }
        }
        mergeAABB(a) {
          a.getBoundary(_min, _max);
          this.mergePoint(_min);
          this.mergePoint(_max);
        }
      }

      const rayPlane = function () {
        return function (ray, plane) {
          const denom = Vec3.dot(ray.d, plane.n);
          if (Math.abs(denom) < Number.EPSILON) {
            return 0;
          }
          const d = point_plane(ray.o, plane);
          const t = -d / denom;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      const rayTriangle = function () {
        const ab = new Vec3(0, 0, 0);
        const ac = new Vec3(0, 0, 0);
        const pvec = new Vec3(0, 0, 0);
        const tvec = new Vec3(0, 0, 0);
        const 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);
          const det = Vec3.dot(ab, pvec);
          if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) {
            return 0;
          }
          const inv_det = 1 / det;
          Vec3.subtract(tvec, ray.o, triangle.a);
          const u = Vec3.dot(tvec, pvec) * inv_det;
          if (u < 0 || u > 1) {
            return 0;
          }
          Vec3.cross(qvec, tvec, ab);
          const v = Vec3.dot(ray.d, qvec) * inv_det;
          if (v < 0 || u + v > 1) {
            return 0;
          }
          const t = Vec3.dot(ac, qvec) * inv_det;
          return t < 0 ? 0 : t;
        };
      }();
      const raySphere = function () {
        const e = new Vec3(0, 0, 0);
        return function (ray, sphere) {
          const r = sphere.radius;
          const c = sphere.center;
          const o = ray.o;
          const d = ray.d;
          const rSq = r * r;
          Vec3.subtract(e, c, o);
          const eSq = e.lengthSqr();
          const aLength = Vec3.dot(e, d);
          const fSq = rSq - (eSq - aLength * aLength);
          if (fSq < 0) {
            return 0;
          }
          const f = Math.sqrt(fSq);
          const t = eSq < rSq ? aLength + f : aLength - f;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      const rayAABB = function () {
        const min = new Vec3();
        const 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) {
        const o = ray.o;
        const d = ray.d;
        const ix = 1 / d.x;
        const iy = 1 / d.y;
        const iz = 1 / d.z;
        const t1 = (min.x - o.x) * ix;
        const t2 = (max.x - o.x) * ix;
        const t3 = (min.y - o.y) * iy;
        const t4 = (max.y - o.y) * iy;
        const t5 = (min.z - o.z) * iz;
        const t6 = (max.z - o.z) * iz;
        const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        const 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;
      }
      const rayOBB = function () {
        let center = new Vec3();
        let o = new Vec3();
        let d = new Vec3();
        const X = new Vec3();
        const Y = new Vec3();
        const Z = new Vec3();
        const p = new Vec3();
        const size = new Array(3);
        const f = new Array(3);
        const e = new Array(3);
        const 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 (let 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];
          }
          const tmin = Math.max(Math.max(Math.min(t[0], t[1]), Math.min(t[2], t[3])), Math.min(t[4], t[5]));
          const 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;
        };
      }();
      const rayCapsule = function () {
        const v3_0 = new Vec3();
        const v3_1 = new Vec3();
        const v3_2 = new Vec3();
        const v3_3 = new Vec3();
        const v3_4 = new Vec3();
        const v3_5 = new Vec3();
        const v3_6 = new Vec3();
        const sphere_0 = new Sphere();
        return function (ray, capsule) {
          const A = capsule.ellipseCenter0;
          const B = capsule.ellipseCenter1;
          const BA = Vec3.subtract(v3_1, B, A);
          if (BA.length() < EPSILON$2) {
            sphere_0.radius = capsule.radius;
            sphere_0.center.set(capsule.ellipseCenter0);
            return intersect.raySphere(ray, sphere_0);
          }
          const O = ray.o;
          const OA = Vec3.subtract(v3_2, O, A);
          const vRayNorm = Vec3.normalize(v3_0, ray.d);
          const VxBA = Vec3.cross(v3_3, vRayNorm, BA);
          const a = VxBA.lengthSqr();
          if (a === 0) {
            sphere_0.radius = capsule.radius;
            const 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);
          }
          const OAxBA = Vec3.cross(v3_4, OA, BA);
          const ab2 = BA.lengthSqr();
          const b = 2 * Vec3.dot(VxBA, OAxBA);
          const radiusSqr = capsule.radius * capsule.radius;
          const c = OAxBA.lengthSqr() - radiusSqr * ab2;
          const d = b * b - 4 * a * c;
          if (d < 0) {
            return 0;
          }
          const t = (-b - Math.sqrt(d)) / (2 * a);
          if (t < 0) {
            sphere_0.radius = capsule.radius;
            const 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 {
            const iPos = Vec3.scaleAndAdd(v3_5, ray.o, vRayNorm, t);
            const iPosLen = Vec3.subtract(v3_6, iPos, A);
            const 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;
            }
          }
        };
      }();
      const linePlane = function () {
        const ab = new Vec3(0, 0, 0);
        return function (line, plane) {
          Vec3.subtract(ab, line.e, line.s);
          const t = -point_plane(line.s, plane) / Vec3.dot(ab, plane.n);
          if (t < 0 || t > 1) {
            return 0;
          }
          return t;
        };
      }();
      const lineTriangle = function () {
        const ab = new Vec3(0, 0, 0);
        const ac = new Vec3(0, 0, 0);
        const qp = new Vec3(0, 0, 0);
        const ap = new Vec3(0, 0, 0);
        const n = new Vec3(0, 0, 0);
        const 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);
          const det = Vec3.dot(qp, n);
          if (det <= 0.0) {
            return 0;
          }
          Vec3.subtract(ap, line.s, triangle.a);
          const t = Vec3.dot(ap, n);
          if (t < 0 || t > det) {
            return 0;
          }
          Vec3.cross(e, qp, ap);
          let v = Vec3.dot(ac, e);
          if (v < 0 || v > det) {
            return 0;
          }
          let w = -Vec3.dot(ab, e);
          if (w < 0.0 || v + w > det) {
            return 0;
          }
          if (outPt) {
            const invDet = 1.0 / det;
            v *= invDet;
            w *= invDet;
            const 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;
        };
      }();
      const 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();
        const min = rayAABB(r_t, aabb);
        const 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();
        const min = rayOBB(r_t, obb);
        const 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();
        const min = raySphere(r_t, sphere);
        const len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      const aabbWithAABB = function () {
        const aMin = new Vec3();
        const aMax = new Vec3();
        const bMin = new Vec3();
        const 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) {
        let min = Vec3.dot(axis, vertices[0]);
        let max = min;
        for (let i = 1; i < 8; ++i) {
          const projection = Vec3.dot(axis, vertices[i]);
          min = projection < min ? projection : min;
          max = projection > max ? projection : max;
        }
        return [min, max];
      }
      const aabbWithOBB = function () {
        const test = new Array(15);
        for (let i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        const vertices = new Array(8);
        const vertices2 = new Array(8);
        for (let i = 0; i < 8; i++) {
          vertices[i] = new Vec3(0, 0, 0);
          vertices2[i] = new Vec3(0, 0, 0);
        }
        const min = new Vec3();
        const 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 (let i = 0; i < 3; ++i) {
            Vec3.cross(test[6 + i * 3 + 0], test[i], test[3]);
            Vec3.cross(test[6 + i * 3 + 1], test[i], test[4]);
            Vec3.cross(test[6 + i * 3 + 1], test[i], 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 (let j = 0; j < 15; ++j) {
            const a = getInterval(vertices, test[j]);
            const b = getInterval(vertices2, test[j]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      const aabbPlane = function (aabb, plane) {
        const 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);
        const dot = Vec3.dot(plane.n, aabb.center);
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      const aabbFrustum = function (aabb, frustum) {
        for (let i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      const aabbFrustumCompletelyInside = function (aabb, frustum) {
        for (let i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) !== 0) {
            return 0;
          }
        }
        return 1;
      };
      const aabbFrustumAccurate = function () {
        const tmp = new Array(8);
        let out1 = 0;
        let out2 = 0;
        for (let i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        return function (aabb, frustum) {
          let result = 0;
          let intersects = false;
          for (let i = 0; i < frustum.planes.length; i++) {
            result = aabbPlane(aabb, frustum.planes[i]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (let i = 0; i < frustum.vertices.length; i++) {
            Vec3.subtract(tmp[i], frustum.vertices[i], aabb.center);
          }
          out1 = 0, out2 = 0;
          for (let i = 0; i < frustum.vertices.length; i++) {
            if (tmp[i].x > aabb.halfExtents.x) {
              out1++;
            } else if (tmp[i].x < -aabb.halfExtents.x) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (let i = 0; i < frustum.vertices.length; i++) {
            if (tmp[i].y > aabb.halfExtents.y) {
              out1++;
            } else if (tmp[i].y < -aabb.halfExtents.y) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (let i = 0; i < frustum.vertices.length; i++) {
            if (tmp[i].z > aabb.halfExtents.z) {
              out1++;
            } else if (tmp[i].z < -aabb.halfExtents.z) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          return 1;
        };
      }();
      const obbPoint = function () {
        const tmp = new Vec3(0, 0, 0);
        const m3 = new Mat3();
        const lessThan = function (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);
        };
      }();
      const obbPlane = function () {
        const absDot = function (n, x, y, z) {
          return Math.abs(n.x * x + n.y * y + n.z * z);
        };
        return function (obb, plane) {
          const 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);
          const dot = Vec3.dot(plane.n, obb.center);
          if (dot + r < plane.d) {
            return -1;
          } else if (dot - r > plane.d) {
            return 0;
          }
          return 1;
        };
      }();
      const obbFrustum = function (obb, frustum) {
        for (let i = 0; i < frustum.planes.length; i++) {
          if (obbPlane(obb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      const obbFrustumAccurate = function () {
        const tmp = new Array(8);
        let dist = 0;
        let out1 = 0;
        let out2 = 0;
        for (let i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        const dot = function (n, x, y, z) {
          return n.x * x + n.y * y + n.z * z;
        };
        return function (obb, frustum) {
          let result = 0;
          let intersects = false;
          for (let i = 0; i < frustum.planes.length; i++) {
            result = obbPlane(obb, frustum.planes[i]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (let i = 0; i < frustum.vertices.length; i++) {
            Vec3.subtract(tmp[i], frustum.vertices[i], obb.center);
          }
          out1 = 0, out2 = 0;
          for (let i = 0; i < frustum.vertices.length; i++) {
            dist = dot(tmp[i], 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 (let i = 0; i < frustum.vertices.length; i++) {
            dist = dot(tmp[i], 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 (let i = 0; i < frustum.vertices.length; i++) {
            dist = dot(tmp[i], 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;
        };
      }();
      const obbWithOBB = function () {
        const test = new Array(15);
        for (let i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        const vertices = new Array(8);
        const vertices2 = new Array(8);
        for (let i = 0; i < 8; i++) {
          vertices[i] = new Vec3(0, 0, 0);
          vertices2[i] = 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 (let i = 0; i < 3; ++i) {
            Vec3.cross(test[6 + i * 3 + 0], test[i], test[3]);
            Vec3.cross(test[6 + i * 3 + 1], test[i], test[4]);
            Vec3.cross(test[6 + i * 3 + 2], test[i], 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 (let i = 0; i < 15; ++i) {
            const a = getInterval(vertices, test[i]);
            const b = getInterval(vertices2, test[i]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      const obbCapsule = function () {
        const sphere_0 = new Sphere();
        const v3_0 = new Vec3();
        const v3_1 = new Vec3();
        const v3_2 = new Vec3();
        const v3_verts8 = new Array(8);
        for (let i = 0; i < 8; i++) {
          v3_verts8[i] = new Vec3();
        }
        const v3_axis8 = new Array(8);
        for (let i = 0; i < 8; i++) {
          v3_axis8[i] = new Vec3();
        }
        return function (obb, capsule) {
          const 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);
            const axes = v3_axis8;
            const a0 = Vec3.copy(axes[0], v3_0);
            const a1 = Vec3.copy(axes[1], v3_1);
            const a2 = Vec3.copy(axes[2], v3_2);
            const C = Vec3.subtract(axes[3], capsule.center, obb.center);
            C.normalize();
            const 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 (let i = 0; i < 8; ++i) {
              const a = getInterval(v3_verts8, axes[i]);
              const d0 = Vec3.dot(axes[i], capsule.ellipseCenter0);
              const d1 = Vec3.dot(axes[i], capsule.ellipseCenter1);
              const max_d = Math.max(d0, d1);
              const min_d = Math.min(d0, d1);
              const d_min = min_d - capsule.radius;
              const d_max = max_d + capsule.radius;
              if (d_min > a[1] || a[0] > d_max) {
                return 0;
              }
            }
            return 1;
          }
        };
      }();
      const spherePlane = function (sphere, plane) {
        const dot = Vec3.dot(plane.n, sphere.center);
        const r = sphere.radius * plane.n.length();
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      const sphereFrustum = function (sphere, frustum) {
        for (let i = 0; i < frustum.planes.length; i++) {
          if (spherePlane(sphere, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      const sphereFrustumAccurate = function () {
        const pt = new Vec3(0, 0, 0);
        const map = [1, -1, 1, -1, 1, -1];
        return function (sphere, frustum) {
          for (let i = 0; i < 6; i++) {
            const plane = frustum.planes[i];
            const r = sphere.radius;
            const c = sphere.center;
            const n = plane.n;
            const d = plane.d;
            const 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 (let j = 0; j < 6; j++) {
              if (j === i || j === i + map[i]) {
                continue;
              }
              const test = frustum.planes[j];
              if (Vec3.dot(test.n, pt) < test.d) {
                return 0;
              }
            }
          }
          return 1;
        };
      }();
      const sphereWithSphere = function (sphere0, sphere1) {
        const r = sphere0.radius + sphere1.radius;
        return Vec3.squaredDistance(sphere0.center, sphere1.center) < r * r;
      };
      const sphereAABB = function () {
        const pt = new Vec3();
        return function (sphere, aabb) {
          pt_point_aabb(pt, sphere.center, aabb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      const sphereOBB = function () {
        const pt = new Vec3();
        return function (sphere, obb) {
          pt_point_obb(pt, sphere.center, obb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      const sphereCapsule = function () {
        const v3_0 = new Vec3();
        const v3_1 = new Vec3();
        return function (sphere, capsule) {
          const r = sphere.radius + capsule.radius;
          const squaredR = r * r;
          const 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);
            const 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;
            }
          }
        };
      }();
      const capsuleWithCapsule = function () {
        const v3_0 = new Vec3();
        const v3_1 = new Vec3();
        const v3_2 = new Vec3();
        const v3_3 = new Vec3();
        const v3_4 = new Vec3();
        const v3_5 = new Vec3();
        return function capsuleWithCapsule(capsuleA, capsuleB) {
          const u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0);
          const v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0);
          const w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0);
          const a = Vec3.dot(u, u);
          const b = Vec3.dot(u, v);
          const c = Vec3.dot(v, v);
          const d = Vec3.dot(u, w);
          const e = Vec3.dot(v, w);
          const D = a * c - b * b;
          let sN;
          let sD = D;
          let tN;
          let tD = D;
          if (D < EPSILON$2) {
            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;
            }
          }
          const sc = Math.abs(sN) < EPSILON$2 ? 0.0 : sN / sD;
          const tc = Math.abs(tN) < EPSILON$2 ? 0.0 : tN / tD;
          const dP = v3_3;
          dP.set(w);
          dP.add(Vec3.multiplyScalar(v3_4, u, sc));
          dP.subtract(Vec3.multiplyScalar(v3_5, v, tc));
          const radius = capsuleA.radius + capsuleB.radius;
          return dP.lengthSqr() < radius * radius;
        };
      }();
      const intersect = {
        raySphere,
        rayAABB,
        rayOBB,
        rayPlane,
        rayTriangle,
        rayCapsule,
        raySubMesh: null,
        rayMesh: null,
        rayModel: null,
        lineSphere,
        lineAABB,
        lineOBB,
        linePlane,
        lineTriangle,
        sphereWithSphere,
        sphereAABB,
        sphereOBB,
        spherePlane,
        sphereFrustum,
        sphereFrustumAccurate,
        sphereCapsule,
        aabbWithAABB,
        aabbWithOBB,
        aabbPlane,
        aabbFrustum,
        aabbFrustumAccurate,
        obbWithOBB,
        obbPlane,
        obbFrustum,
        obbFrustumAccurate,
        obbPoint,
        obbCapsule,
        aabbFrustumCompletelyInside,
        capsuleWithCapsule,
        resolve(g1, g2, outPt = null) {
          const type1 = g1._type;
          const type2 = g2._type;
          const resolver = this[type1 | type2];
          return type1 < type2 ? resolver(g1, g2, outPt) : resolver(g2, g1, outPt);
        }
      };
      intersect[1 | 4] = raySphere;
      intersect[1 | 8] = rayAABB;
      intersect[1 | 16] = rayOBB;
      intersect[1 | 32] = rayPlane;
      intersect[1 | 64] = rayTriangle;
      intersect[1 | 512] = rayCapsule;
      intersect[2 | 4] = lineSphere;
      intersect[2 | 8] = lineAABB;
      intersect[2 | 16] = lineOBB;
      intersect[2 | 32] = linePlane;
      intersect[2 | 64] = lineTriangle;
      intersect[4] = sphereWithSphere;
      intersect[4 | 8] = sphereAABB;
      intersect[4 | 16] = sphereOBB;
      intersect[4 | 32] = spherePlane;
      intersect[4 | 128] = sphereFrustum;
      intersect[4 | 256] = sphereFrustumAccurate;
      intersect[4 | 512] = sphereCapsule;
      intersect[8] = aabbWithAABB;
      intersect[8 | 16] = aabbWithOBB;
      intersect[8 | 32] = aabbPlane;
      intersect[8 | 128] = aabbFrustum;
      intersect[8 | 256] = aabbFrustumAccurate;
      intersect[16] = obbWithOBB;
      intersect[16 | 32] = obbPlane;
      intersect[16 | 128] = obbFrustum;
      intersect[16 | 256] = obbFrustumAccurate;
      intersect[16 | 512] = obbCapsule;
      intersect[512] = capsuleWithCapsule;

      replaceProperty(Line.prototype, 'line', [{
        name: 'mag',
        newName: 'len'
      }, {
        name: 'magnitude',
        newName: 'len'
      }]);
      removeProperty(intersect, 'intersect', [{
        name: 'line_quad'
      }]);

      const v1 = new Vec3(0, 0, 0);
      const v2 = new Vec3(0, 0, 0);
      const temp_mat = mat4();
      const temp_vec4 = v4();
      class Plane {
        static create(nx, ny, nz, d) {
          return new Plane(nx, ny, nz, d);
        }
        static clone(p) {
          return new Plane(p.n.x, p.n.y, p.n.z, p.d);
        }
        static copy(out, p) {
          Vec3.copy(out.n, p.n);
          out.d = p.d;
          return out;
        }
        static 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;
        }
        static set(out, nx, ny, nz, d) {
          out.n.x = nx;
          out.n.y = ny;
          out.n.z = nz;
          out.d = d;
          return out;
        }
        static fromNormalAndPoint(out, normal, point) {
          Vec3.copy(out.n, normal);
          out.d = Vec3.dot(normal, point);
          return out;
        }
        static normalize(out, a) {
          const len = a.n.length();
          Vec3.normalize(out.n, a.n);
          if (len > 0) {
            out.d = a.d / len;
          }
          return out;
        }
        get type() {
          return this._type;
        }
        set x(val) {
          this.n.x = val;
        }
        get x() {
          return this.n.x;
        }
        set y(val) {
          this.n.y = val;
        }
        get y() {
          return this.n.y;
        }
        set z(val) {
          this.n.z = val;
        }
        get z() {
          return this.n.z;
        }
        set w(val) {
          this.d = val;
        }
        get w() {
          return this.d;
        }
        constructor(nx = 0, ny = 1, nz = 0, d = 0) {
          this._type = 32;
          this.n = new Vec3(nx, ny, nz);
          this.d = d;
        }
        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;
        }
      }

      class Triangle {
        static create(ax = 1, ay = 0, az = 0, bx = 0, by = 0, bz = 0, cx = 0, cy = 0, cz = 1) {
          return new Triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
        }
        static 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);
        }
        static copy(out, t) {
          Vec3.copy(out.a, t.a);
          Vec3.copy(out.b, t.b);
          Vec3.copy(out.c, t.c);
          return out;
        }
        static fromPoints(out, a, b, c) {
          Vec3.copy(out.a, a);
          Vec3.copy(out.b, b);
          Vec3.copy(out.c, c);
          return out;
        }
        static 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;
        }
        get type() {
          return this._type;
        }
        constructor(ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, cx = 0, cy = 1, cz = 0) {
          this._type = 64;
          this.a = new Vec3(ax, ay, az);
          this.b = new Vec3(bx, by, bz);
          this.c = new Vec3(cx, cy, cz);
        }
      }

      deprecateModuleExportedName({
        replaceProperty: {
          since: '3.6.0',
          removed: false
        },
        removeProperty: {
          since: '3.6.0',
          removed: false
        },
        markAsWarning: {
          since: '3.6.0',
          removed: false
        },
        setDefaultLogTimes: {
          since: '3.6.0',
          removed: false
        }
      });

      class ScalableContainer {
        constructor() {
          this._poolHandle = -1;
          scalableContainerManager.addContainer(this);
        }
        destroy() {
          scalableContainerManager.removeContainer(this);
        }
      }
      class ScalableContainerManager {
        constructor() {
          this._pools = [];
          this._lastShrinkPassed = 0;
          this.shrinkTimeSpan = 5;
        }
        addContainer(pool) {
          if (pool._poolHandle !== -1) return;
          pool._poolHandle = this._pools.length;
          this._pools.push(pool);
        }
        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;
        }
        tryShrink() {
          for (let i = 0; i < this._pools.length; i++) {
            this._pools[i].tryShrink();
          }
        }
        update(dt) {
          this._lastShrinkPassed += dt;
          if (this._lastShrinkPassed > this.shrinkTimeSpan) {
            this.tryShrink();
            this._lastShrinkPassed -= this.shrinkTimeSpan;
          }
        }
      }
      const scalableContainerManager = new ScalableContainerManager();

      class Pool extends ScalableContainer {
        constructor(ctor, elementsPerBatch, dtor, shrinkThreshold) {
          super();
          this._freePool = [];
          this._ctor = ctor;
          this._dtor = dtor || null;
          this._elementsPerBatch = Math.max(elementsPerBatch, 1);
          this._shrinkThreshold = shrinkThreshold ? max$b(shrinkThreshold, 1) : this._elementsPerBatch;
          this._nextAvail = this._elementsPerBatch - 1;
          for (let i = 0; i < this._elementsPerBatch; ++i) {
            this._freePool.push(ctor());
          }
        }
        alloc() {
          if (this._nextAvail < 0) {
            this._freePool.length = this._elementsPerBatch;
            for (let i = 0; i < this._elementsPerBatch; i++) {
              this._freePool[i] = this._ctor();
            }
            this._nextAvail = this._elementsPerBatch - 1;
          }
          return this._freePool[this._nextAvail--];
        }
        free(obj) {
          this._freePool[++this._nextAvail] = obj;
        }
        freeArray(objs) {
          this._freePool.length = this._nextAvail + 1;
          Array.prototype.push.apply(this._freePool, objs);
          this._nextAvail += objs.length;
        }
        tryShrink() {
          const freeObjectNumber = this._nextAvail + 1;
          if (freeObjectNumber <= this._shrinkThreshold) {
            return;
          }
          let objectNumberToShrink = 0;
          if (freeObjectNumber >> 1 >= this._shrinkThreshold) {
            objectNumberToShrink = freeObjectNumber >> 1;
          } else {
            objectNumberToShrink = Math.floor((freeObjectNumber - this._shrinkThreshold + 1) / 2);
          }
          if (this._dtor) {
            for (let i = this._nextAvail - objectNumberToShrink + 1; i <= this._nextAvail; ++i) {
              this._dtor(this._freePool[i]);
            }
          }
          this._nextAvail -= objectNumberToShrink;
          this._freePool.length = this._nextAvail + 1;
        }
        destroy() {
          const dtor = arguments.length > 0 ? arguments[0] : null;
          if (dtor) {
            warnID(14100);
          }
          const readDtor = dtor || this._dtor;
          if (readDtor) {
            for (let i = 0; i <= this._nextAvail; i++) {
              readDtor(this._freePool[i]);
            }
          }
          this._freePool.length = 0;
          this._nextAvail = -1;
          super.destroy();
        }
      } exports("Pool", Pool);

      class RecyclePool extends ScalableContainer {
        constructor(fn, size, dtor) {
          super();
          this._count = 0;
          this._fn = fn;
          this._dtor = dtor || null;
          this._data = new Array(size);
          this._initSize = size;
          for (let i = 0; i < size; ++i) {
            this._data[i] = fn();
          }
        }
        get length() {
          return this._count;
        }
        get data() {
          return this._data;
        }
        reset() {
          this._count = 0;
        }
        resize(size) {
          if (size > this._data.length) {
            for (let i = this._data.length; i < size; ++i) {
              this._data[i] = this._fn();
            }
          }
        }
        add() {
          if (this._count >= this._data.length) {
            this.resize(this._data.length << 1);
          }
          return this._data[this._count++];
        }
        destroy() {
          if (this._dtor) {
            for (let i = 0; i < this._data.length; i++) {
              this._dtor(this._data[i]);
            }
          }
          this._data.length = 0;
          this._count = 0;
          super.destroy();
        }
        tryShrink() {
          if (this._data.length >> 2 > this._count) {
            const length = Math.max(this._initSize, this._data.length >> 1);
            if (this._dtor) {
              for (let i = length; i < this._data.length; i++) {
                this._dtor(this._data[i]);
              }
            }
            this._data.length = length;
          }
        }
        removeAt(idx) {
          if (idx >= this._count) {
            return;
          }
          const last = this._count - 1;
          const tmp = this._data[idx];
          this._data[idx] = this._data[last];
          this._data[last] = tmp;
          this._count -= 1;
        }
      } exports("RecyclePool", RecyclePool);

      class CachedArray extends ScalableContainer {
        constructor(length, compareFn) {
          super();
          this.length = 0;
          this._initSize = 0;
          this.array = new Array(length);
          this._initSize = length;
          this._compareFn = compareFn;
        }
        push(item) {
          this.array[this.length++] = item;
        }
        pop() {
          return this.array[--this.length];
        }
        get(idx) {
          return this.array[idx];
        }
        clear() {
          this.length = 0;
        }
        destroy() {
          this.length = 0;
          this.array.length = 0;
          super.destroy();
        }
        tryShrink() {
          if (this.array.length >> 2 > this.length) {
            this.array.length = Math.max(this._initSize, this.array.length >> 1);
          }
        }
        sort() {
          this.array.length = this.length;
          this.array.sort(this._compareFn);
        }
        concat(array) {
          for (let i = 0; i < array.length; ++i) {
            this.array[this.length++] = array[i];
          }
        }
        fastRemove(idx) {
          if (idx >= this.length || idx < 0) {
            return;
          }
          const last = --this.length;
          this.array[idx] = this.array[last];
        }
        indexOf(val) {
          for (let i = 0, len = this.length; i < len; ++i) {
            if (this.array[i] === val) {
              return i;
            }
          }
          return -1;
        }
      } exports("CachedArray", CachedArray);

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

      const editorExtrasTag = exports("editorExtrasTag", '__editorExtras__');

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

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

      function Eventify(base) {
        class Eventified extends base {
          constructor(...args) {
            super(...args);
            this._callbackTable = createMap(true);
          }
          once(type, callback, target) {
            return this.on(type, callback, target, true);
          }
          targetOff(typeOrTarget) {
            this.removeAll(typeOrTarget);
          }
        }
        const callbacksInvokerPrototype = CallbacksInvoker.prototype;
        const propertyKeys = Object.getOwnPropertyNames(callbacksInvokerPrototype).concat(Object.getOwnPropertySymbols(callbacksInvokerPrototype));
        for (let iPropertyKey = 0; iPropertyKey < propertyKeys.length; ++iPropertyKey) {
          const propertyKey = propertyKeys[iPropertyKey];
          if (!(propertyKey in Eventified.prototype)) {
            const propertyDescriptor = Object.getOwnPropertyDescriptor(callbacksInvokerPrototype, propertyKey);
            if (propertyDescriptor) {
              Object.defineProperty(Eventified.prototype, propertyKey, propertyDescriptor);
            }
          }
        }
        return Eventified;
      }

      let Empty$1 = class Empty {};
      const EventTarget = exports("EventTarget", Eventify(Empty$1));
      legacyCC.EventTarget = EventTarget;

      class AsyncDelegate {
        constructor() {
          this._delegates = [];
        }
        add(callback) {
          if (!this._delegates.includes(callback)) {
            this._delegates.push(callback);
          }
        }
        hasListener(callback) {
          return this._delegates.includes(callback);
        }
        remove(callback) {
          fastRemove(this._delegates, callback);
        }
        dispatch(...args) {
          return Promise.all(this._delegates.map(func => func(...arguments)).filter(Boolean));
        }
      } exports("AsyncDelegate", AsyncDelegate);

      let 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 = {}));

      let 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 = {}));

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

      let 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 = {}));

      let 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["MIGU_MINI_GAME"] = "MIGU_MINI_GAME";
      })(Platform || (Platform = {}));

      let 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 = {}));

      const networkTypeMap = {
        0: NetworkType.NONE,
        1: NetworkType.LAN,
        2: NetworkType.WWAN
      };
      const platformMap = {
        0: Platform.WIN32,
        2: Platform.MACOS,
        3: Platform.ANDROID,
        4: Platform.IOS,
        5: Platform.IOS,
        6: Platform.OHOS,
        7: Platform.OPENHARMONY
      };
      class SystemInfo extends EventTarget {
        get networkType() {
          return networkTypeMap[jsb.device.getNetworkType()];
        }
        constructor() {
          super();
          this._initPromise = [];
          this.isNative = true;
          this.isBrowser = false;
          this.platform = platformMap[__getPlatform()];
          this.isMobile = this.platform === Platform.ANDROID || this.platform === Platform.IOS || this.platform === Platform.OHOS || this.platform === Platform.OPENHARMONY;
          this.isLittleEndian = (() => {
            const buffer = new ArrayBuffer(2);
            new DataView(buffer).setInt16(0, 256, true);
            return new Int16Array(buffer)[0] === 256;
          })();
          const currLanguage = __getCurrentLanguageCode();
          this.nativeLanguage = currLanguage ? currLanguage.toLowerCase() : Language.UNKNOWN;
          this.language = __getCurrentLanguage();
          this.os = __getOS();
          this.osVersion = __getOSVersion();
          this.osMainVersion = parseInt(this.osVersion);
          this.browserType = BrowserType.UNKNOWN;
          this.browserVersion = '';
          this.isXR = typeof xr !== 'undefined' && typeof xr.XrEntry !== 'undefined';
          const isHPE = typeof __supportHPE === 'function' ? __supportHPE() : false;
          this._featureMap = {
            [Feature$1.WEBP]: true,
            [Feature$1.IMAGE_BITMAP]: false,
            [Feature$1.WEB_VIEW]: this.isMobile,
            [Feature$1.VIDEO_PLAYER]: this.isMobile,
            [Feature$1.SAFE_AREA]: this.isMobile,
            [Feature$1.HPE]: isHPE,
            [Feature$1.INPUT_TOUCH]: this.isMobile,
            [Feature$1.EVENT_KEYBOARD]: true,
            [Feature$1.EVENT_MOUSE]: isHPE || !this.isMobile,
            [Feature$1.EVENT_TOUCH]: true,
            [Feature$1.EVENT_ACCELEROMETER]: this.isMobile,
            [Feature$1.EVENT_GAMEPAD]: true,
            [Feature$1.EVENT_HANDLE]: this.isXR,
            [Feature$1.EVENT_HMD]: this.isXR,
            [Feature$1.EVENT_HANDHELD]: typeof xr !== 'undefined' && typeof xr.ARModule !== 'undefined',
            [Feature$1.WASM]: !OPEN_HARMONY
          };
          this._registerEvent();
        }
        _registerEvent() {
          jsb.onPause = () => {
            this.emit('hide');
          };
          jsb.onResume = () => {
            this.emit('show');
          };
          jsb.onClose = () => {
            this.emit('close');
          };
        }
        _setFeature(feature, value) {
          return this._featureMap[feature] = value;
        }
        init() {
          return Promise.all(this._initPromise);
        }
        hasFeature(feature) {
          return this._featureMap[feature];
        }
        getBatteryLevel() {
          return jsb.device.getBatteryLevel();
        }
        triggerGC() {
          jsb.garbageCollect();
        }
        openURL(url) {
          jsb.openURL(url);
        }
        now() {
          if (Date.now) {
            return Date.now();
          }
          return +new Date();
        }
        restartJSVM() {
          __restartVM();
        }
        close() {
          __close();
        }
        exit() {
          __exit();
        }
      }
      const systemInfo = new SystemInfo();

      const EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
      const DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
      const NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
      function join(...segments) {
        let result = '';
        for (const segment of segments) {
          result = (result + (result === '' ? '' : '/') + segment).replace(/(\/|\\\\)$/, '');
        }
        return result;
      }
      function extname(path) {
        const temp = EXTNAME_RE.exec(path);
        return temp ? temp[1] : '';
      }
      function mainFileName(fileName) {
        if (fileName) {
          const idx = fileName.lastIndexOf('.');
          if (idx !== -1) {
            return fileName.substring(0, idx);
          }
        }
        return fileName;
      }
      function basename(path, extName) {
        const index = path.indexOf('?');
        if (index > 0) {
          path = path.substring(0, index);
        }
        const reg = /(\/|\\)([^\/\\]+)$/g;
        const result = reg.exec(path.replace(/(\/|\\)$/, ''));
        if (!result) {
          return path;
        }
        const 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) {
        const temp = DIRNAME_RE.exec(path);
        return temp ? temp[2] : '';
      }
      function changeExtname(path, extName) {
        extName = extName || '';
        let index = path.indexOf('?');
        let 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);
        }
        let index = path.indexOf('?');
        let tempStr = '';
        const 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) {
        let 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,
        _normalize: _normalize,
        basename: basename,
        changeBasename: changeBasename,
        changeExtname: changeExtname,
        dirname: dirname,
        extname: extname,
        getSeperator: getSeperator,
        join: join,
        mainFileName: mainFileName,
        stripSep: stripSep
      });
      exports("path", path);

      const _vec3 = new Vec3();
      function WorldNode3DToLocalNodeUI(mainCamera, wpos, uiNode, out) {
        if (!out) {
          out = new Vec3();
        }
        mainCamera.convertToUINode(wpos, uiNode, out);
        const 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;
      }
      const convertUtils = exports("convertUtils", {
        WorldNode3DToLocalNodeUI,
        WorldNode3DToWorldNodeUI
      });
      legacyCC.pipelineUtils = convertUtils;
      replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [{
        name: 'WorldNode3DToLocalNodeUI',
        newName: 'convertToUINode',
        targetName: 'cc.Camera.prototype',
        customFunction(...args) {
          const camera = args[0];
          const out = args[3] || _vec3;
          camera.convertToUINode(args[1], args[2], out);
          out.add(args[2].position);
          return args[3] || out.clone();
        }
      }]);

      const orientationMap$1 = {
        0: Orientation$1.PORTRAIT,
        '-90': Orientation$1.LANDSCAPE_LEFT,
        90: Orientation$1.LANDSCAPE_RIGHT,
        180: Orientation$1.PORTRAIT_UPSIDE_DOWN
      };
      class ScreenAdapter extends EventTarget {
        get supportFullScreen() {
          return false;
        }
        get isFullScreen() {
          return false;
        }
        get devicePixelRatio() {
          return jsb.device.getDevicePixelRatio() || 1;
        }
        get windowSize() {
          const dpr = this.devicePixelRatio;
          const width = jsb.window.innerWidth;
          const height = jsb.window.innerHeight;
          const roundWidth = Math.round(width);
          const roundHeight = Math.round(height);
          return new Size$1(roundWidth * dpr, roundHeight * dpr);
        }
        set windowSize(size) {
          warn('Setting window size is not supported yet.');
        }
        get resolution() {
          const windowSize = this.windowSize;
          const resolutionScale = this.resolutionScale;
          return new Size$1(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
        }
        get resolutionScale() {
          return this._resolutionScale;
        }
        set resolutionScale(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);
        }
        get orientation() {
          return orientationMap$1[jsb.device.getDeviceOrientation()];
        }
        set orientation(value) {
          warnID(1221);
        }
        get safeAreaEdge() {
          const nativeSafeArea = jsb.device.getSafeAreaEdge();
          const dpr = this.devicePixelRatio;
          const topEdge = nativeSafeArea.x * dpr;
          const bottomEdge = nativeSafeArea.z * dpr;
          const leftEdge = nativeSafeArea.y * dpr;
          const rightEdge = nativeSafeArea.w * dpr;
          return {
            top: topEdge,
            bottom: bottomEdge,
            left: leftEdge,
            right: rightEdge
          };
        }
        get isProportionalToFrame() {
          return this._isProportionalToFrame;
        }
        set isProportionalToFrame(v) {}
        constructor() {
          super();
          this.isFrameRotated = false;
          this.handleResizeEvent = true;
          this._cbToUpdateFrameBuffer = void 0;
          this._resolutionScale = 1;
          this._isProportionalToFrame = false;
          this._registerEvent();
        }
        init(options, cbToRebuildFrameBuffer) {
          this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
          {
            this._cbToUpdateFrameBuffer();
          }
        }
        requestFullScreen() {
          return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.'));
        }
        exitFullScreen() {
          return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.'));
        }
        _registerEvent() {
          jsb.onResize = event => {
            if (event.width === 0 || event.height === 0) return;
            window.resize(event.width / this.devicePixelRatio, event.height / this.devicePixelRatio);
            this.emit('window-resize', event.width, event.height, event.windowId);
          };
          jsb.onOrientationChanged = event => {
            this.emit('orientation-change', this.orientation);
          };
        }
      }
      const screenAdapter = new ScreenAdapter();

      class Screen {
        init() {
          var _settings$querySettin, _settings$querySettin2;
          const exactFitScreen = (_settings$querySettin = settings.querySettings("screen", 'exactFitScreen')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : true;
          const orientation = (_settings$querySettin2 = settings.querySettings("screen", 'orientation')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 'auto';
          const isHeadlessMode = settings.querySettings("rendering", 'renderMode') === 3;
          screenAdapter.init({
            exactFitScreen,
            configOrientation: orientation,
            isHeadlessMode
          }, () => {
            var _director$root;
            const 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;
          });
        }
        get devicePixelRatio() {
          return screenAdapter.devicePixelRatio;
        }
        get windowSize() {
          return screenAdapter.windowSize;
        }
        set windowSize(size) {
          screenAdapter.windowSize = size;
        }
        get resolution() {
          return screenAdapter.resolution;
        }
        get supportsFullScreen() {
          return screenAdapter.supportFullScreen;
        }
        fullScreen() {
          return screenAdapter.isFullScreen;
        }
        requestFullScreen(element, onFullScreenChange, onFullScreenError) {
          if (arguments.length > 0) {
            warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
          }
          return screenAdapter.requestFullScreen().then(() => {
            onFullScreenChange === null || onFullScreenChange === void 0 ? void 0 : onFullScreenChange.call(document);
          }).catch(err => {
            error(err);
            onFullScreenError === null || onFullScreenError === void 0 ? void 0 : onFullScreenError.call(document);
          });
        }
        exitFullScreen() {
          return screenAdapter.exitFullScreen();
        }
        autoFullScreen(element, onFullScreenChange) {
          var _this$requestFullScre;
          (_this$requestFullScre = this.requestFullScreen(element, onFullScreenChange)) === null || _this$requestFullScre === void 0 ? void 0 : _this$requestFullScre.catch(e => {
            warn(e);
          });
        }
        disableAutoFullScreen(element) {}
        on(type, callback, target) {
          screenAdapter.on(type, callback, target);
        }
        once(type, callback, target) {
          screenAdapter.once(type, callback, target);
        }
        off(type, callback, target) {
          screenAdapter.off(type, callback, target);
        }
      }
      const screen = exports("screen", new Screen());
      legacyCC.screen = screen;

      const sys = exports("sys", {
        Feature: Feature$1,
        hasFeature(feature) {
          return systemInfo.hasFeature(feature);
        },
        NetworkType,
        Language,
        OS,
        Platform,
        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() {
          return systemInfo.networkType;
        },
        getBatteryLevel() {
          return systemInfo.getBatteryLevel();
        },
        garbageCollect() {
          systemInfo.triggerGC();
        },
        isObjectValid(obj) {
          if (obj === null || obj === undefined) {
            return false;
          }
          return true;
        },
        __isWebIOS14OrIPadOS14Env: false,
        dump() {
          let 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(url) {
          systemInfo.openURL(url);
        },
        init() {
          return Promise.resolve().then(() => systemInfo.init()).then(() => {
            try {
              let localStorage = sys.localStorage = window.localStorage;
              localStorage.setItem('storage', '');
              localStorage.removeItem('storage');
              localStorage = null;
            } catch (e) {
              const warn = function warn(...args) {
                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() {
          return systemInfo.now();
        },
        restartVM() {
          systemInfo.restartJSVM();
        },
        getSafeAreaRect(symmetric = true) {
          const locView = legacyCC.view;
          const edge = screenAdapter.safeAreaEdge;
          if (symmetric) {
            if (screenAdapter.orientation === macro.ORIENTATION_PORTRAIT) {
              if (edge.top < edge.bottom) {
                edge.top = edge.bottom;
              } else {
                edge.bottom = edge.top;
              }
            } else if (edge.left < edge.right) {
              edge.left = edge.right;
            } else {
              edge.right = edge.left;
            }
          }
          const windowSize = screenAdapter.windowSize;
          const leftBottom = new Vec2(edge.left, edge.bottom);
          const rightTop = new Vec2(windowSize.width - edge.right, windowSize.height - edge.top);
          locView._convertToUISpace(leftBottom);
          locView._convertToUISpace(rightTop);
          const x = leftBottom.x;
          const y = leftBottom.y;
          const width = rightTop.x - leftBottom.x;
          const height = rightTop.y - leftBottom.y;
          return new Rect$1(x, y, width, height);
        }
      });
      legacyCC.sys = sys;

      markAsWarning(legacyCC, 'cc', [{
        name: 'winSize',
        suggest: 'please use view.getVisibleSize() instead.'
      }]);
      markAsWarning(sys, 'sys', [{
        name: 'capabilities',
        suggest: 'please use sys.hasFeature() method instead.'
      }]);
      replaceProperty(sys, 'sys', ['UNKNOWN', 'ENGLISH', 'CHINESE', 'FRENCH', 'ITALIAN', 'GERMAN', 'SPANISH', 'DUTCH', 'RUSSIAN', 'KOREAN', 'JAPANESE', 'HUNGARIAN', 'PORTUGUESE', 'ARABIC', 'NORWEGIAN', 'POLISH', 'TURKISH', 'UKRAINIAN', 'ROMANIAN', 'BULGARIAN'].map(item => ({
        name: `LANGUAGE_${item}`,
        newName: item,
        target: sys.Language,
        targetName: 'sys.Language'
      })));
      replaceProperty(sys, 'sys', ['UNKNOWN', 'IOS', 'ANDROID', 'WINDOWS', 'LINUX', 'OSX'].map(item => ({
        name: `OS_${item}`,
        newName: item,
        target: sys.OS,
        targetName: 'sys.OS'
      })));
      replaceProperty(sys, 'sys', ['UNKNOWN', 'WECHAT', 'ANDROID', 'IE', 'EDGE', 'QQ', 'MOBILE_QQ', 'UC', 'UCBS', 'BAIDU_APP', 'BAIDU', 'MAXTHON', 'OPERA', 'OUPENG', 'MIUI', 'FIREFOX', 'SAFARI', 'CHROME', 'LIEBAO', 'QZONE', 'SOUGOU', 'HUAWEI'].map(item => ({
        name: `BROWSER_TYPE_${item}`,
        newName: item,
        target: sys.BrowserType,
        targetName: 'sys.BrowserType'
      })));
      replaceProperty(sys, 'sys', [{
        name: 'BROWSER_TYPE_360',
        newName: 'BROWSER_360',
        target: sys.BrowserType,
        targetName: 'sys.BrowserType'
      }]);
      replaceProperty(sys, 'sys', ['UNKNOWN', 'EDITOR_PAGE', 'EDITOR_CORE', 'MOBILE_BROWSER', 'DESKTOP_BROWSER', 'WIN32', 'MACOS', 'IOS', 'ANDROID', 'OHOS', 'WECHAT_GAME', 'BAIDU_MINI_GAME', 'XIAOMI_QUICK_GAME', 'ALIPAY_MINI_GAME', 'BYTEDANCE_MINI_GAME', 'OPPO_MINI_GAME', 'VIVO_MINI_GAME', 'HUAWEI_QUICK_GAME', 'COCOSPLAY', 'LINKSURE_MINI_GAME', 'QTT_MINI_GAME'].map(item => ({
        name: item,
        target: sys.Platform,
        targetName: 'sys.Platform'
      })));
      replaceProperty(sys, 'sys', [{
        name: 'IPHONE',
        newName: 'IOS',
        target: sys.Platform,
        targetName: 'sys.Platform'
      }, {
        name: 'IPAD',
        newName: 'IOS',
        target: sys.Platform,
        targetName: 'sys.Platform'
      }]);
      removeProperty(sys, 'sys', ['LINUX', 'BLACKBERRY', 'NACL', 'EMSCRIPTEN', 'TIZEN', 'WINRT', 'WP8', 'QQ_PLAY', 'FB_PLAYABLE_ADS'].map(item => ({
        name: item
      })));
      replaceProperty(sys, 'sys', [{
        name: 'windowPixelResolution',
        target: screen,
        targetName: 'screen',
        newName: 'windowSize'
      }]);
      markAsWarning(screen, 'screen', [{
        name: 'autoFullScreen',
        suggest: 'please use screen.requestFullScreen() instead.'
      }, {
        name: 'disableAutoFullScreen'
      }]);

      const visibleRect = exports("visibleRect", {
        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(visibleRect_) {
          const w = this.width = visibleRect_.width;
          const h = this.height = visibleRect_.height;
          const l = visibleRect_.x;
          const b = visibleRect_.y;
          const t = b + h;
          const 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;

      const _v3_tmp$1 = new Vec3();
      const _v3_tmp2$1 = new Vec3();
      const _v3_tmp3 = new Vec3();
      const _v3_tmp4 = new Vec3();
      const _m3_tmp$1 = new Mat3();
      const 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);
      };
      class AABB {
        static create(px, py, pz, hw, hh, hl) {
          return new AABB(px, py, pz, hw, hh, hl);
        }
        static clone(a) {
          {
            warn('The static method AABB.clone has been deprecated. Please use the corresponding instance method instead.');
          }
          return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z);
        }
        static copy(out, a) {
          {
            warn('The static method AABB.copy has been deprecated. Please use the corresponding instance method instead.');
          }
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          return out;
        }
        static 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;
        }
        static set(out, px, py, pz, hw, hh, hl) {
          out.center.set(px, py, pz);
          out.halfExtents.set(hw, hh, hl);
          return out;
        }
        static 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);
        }
        static toBoundingSphere(out, a) {
          out.center.set(a.center);
          out.radius = a.halfExtents.length();
          return out;
        }
        static transform(out, a, matrix) {
          Vec3.transformMat4(out.center, a.center, matrix);
          transform_extent_m4(out.halfExtents, a.halfExtents, matrix);
          return out;
        }
        get type() {
          return this._type;
        }
        constructor(px = 0, py = 0, pz = 0, hw = 1, hh = 1, hl = 1) {
          this.center = void 0;
          this.halfExtents = void 0;
          this._type = void 0;
          this._type = 8;
          this.center = new Vec3(px, py, pz);
          this.halfExtents = new Vec3(hw, hh, hl);
        }
        getBoundary(minPos, maxPos) {
          Vec3.subtract(minPos, this.center, this.halfExtents);
          Vec3.add(maxPos, this.center, this.halfExtents);
        }
        transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          transform_extent_m4(out.halfExtents, this.halfExtents, m);
        }
        clone() {
          const center = this.center;
          const halfExtents = this.halfExtents;
          return new AABB(center.x, center.y, center.z, halfExtents.x, halfExtents.y, halfExtents.z);
        }
        copy(a) {
          Vec3.copy(this.center, a.center);
          Vec3.copy(this.halfExtents, a.halfExtents);
          return this;
        }
        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);
        }
        mergePoints(points) {
          if (points.length < 1) {
            return;
          }
          for (let i = 0; i < points.length; i++) {
            this.mergePoint(points[i]);
          }
        }
        mergeFrustum(frustum) {
          this.mergePoints(frustum.vertices);
        }
      }

      class Capsule {
        get type() {
          return this._type;
        }
        constructor(radius = 0.5, halfHeight = 0.5, 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 = 512;
          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();
        }
        transform(m, pos, rot, scale, out) {
          const ws = scale;
          const s = absMaxComponent(ws);
          out.radius = this.radius * Math.abs(s);
          const halfTotalWorldHeight = (this.halfHeight + this.radius) * Math.abs(ws.y);
          let 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();
        }
        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);
        }
        updateLocalCenter() {
          const halfHeight = this.halfHeight;
          const 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;
          }
        }
      }

      const _v = new Array(8);
      _v[0] = v3(1, 1, 1);
      _v[1] = v3(-1, 1, 1);
      _v[2] = v3(-1, -1, 1);
      _v[3] = v3(1, -1, 1);
      _v[4] = v3(1, 1, -1);
      _v[5] = v3(-1, 1, -1);
      _v[6] = v3(-1, -1, -1);
      _v[7] = v3(1, -1, -1);
      const _nearTemp = v3();
      const _farTemp = v3();
      const _temp_v3 = v3();
      class Frustum {
        static createOrthographic(out, width, height, near, far, transform) {
          const halfWidth = width / 2;
          const 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();
        }
        static createOrtho(out, width, height, near, far, transform) {
          return Frustum.createOrthographic(out, width, height, near, far, transform);
        }
        static createPerspective(out, aspect, fov, near, far, transform) {
          const h = Math.tan(fov * 0.5);
          const w = h * aspect;
          _nearTemp.set(near * w, near * h, near);
          _farTemp.set(far * w, far * h, far);
          const 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();
        }
        static createFromAABB(out, aabb) {
          const vec3_min = new Vec3();
          const 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;
        }
        split(start, end, aspect, fov, m) {
          return Frustum.createPerspective(this, aspect, fov, start, end, m);
        }
        static create() {
          return new Frustum();
        }
        static clone(f) {
          return Frustum.copy(new Frustum(), f);
        }
        static copy(out, f) {
          out._type = f.type;
          for (let i = 0; i < 6; ++i) {
            Plane.copy(out.planes[i], f.planes[i]);
          }
          for (let i = 0; i < 8; ++i) {
            Vec3.copy(out.vertices[i], f.vertices[i]);
          }
          return out;
        }
        set accurate(b) {
          this._type = b ? 256 : 128;
        }
        get type() {
          return this._type;
        }
        constructor() {
          this.planes = void 0;
          this.vertices = void 0;
          this._type = void 0;
          this._type = 128;
          this.planes = new Array(6);
          for (let i = 0; i < 6; ++i) {
            this.planes[i] = Plane.create(0, 0, 0, 0);
          }
          this.vertices = new Array(8);
          for (let i = 0; i < 8; ++i) {
            this.vertices[i] = new Vec3();
          }
        }
        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 (let i = 0; i < 6; i++) {
            const pl = this.planes[i];
            const invDist = 1 / pl.n.length();
            Vec3.multiplyScalar(pl.n, pl.n, invDist);
            pl.d *= invDist;
          }
          for (let i = 0; i < 8; i++) {
            Vec3.transformMat4(this.vertices[i], _v[i], inv);
          }
        }
        transform(mat) {
          for (let i = 0; i < 8; i++) {
            Vec3.transformMat4(this.vertices[i], this.vertices[i], mat);
          }
          this.updatePlanes();
        }
        zero() {
          for (let i = 0; i < 8; i++) {
            this.vertices[i].set(0.0, 0.0, 0.0);
          }
          for (let i = 0; i < 6; i++) {
            Plane.set(this.planes[i], 0, 0, 0, 0);
          }
        }
        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]);
        }
      }

      function cacheProperty(ctor, property) {
        const propDesc = Object.getOwnPropertyDescriptor(ctor.prototype, property);
        const propCacheKey = `_$cache_${property}`;
        const propRealKey = `_$_${property}`;
        Object.defineProperty(ctor.prototype, propRealKey, propDesc);
        Object.defineProperty(ctor.prototype, property, {
          get() {
            if (this[propCacheKey] === undefined) {
              this[propCacheKey] = this[propRealKey];
            }
            return this[propCacheKey];
          },
          set(value) {
            this[propRealKey] = value;
          },
          configurable: true,
          enumerable: true
        });
      }
      function cacheUnderlyingData(ctor) {
        ctor.prototype._arraybuffer = function () {
          if (!this.__data) {
            this.__data = this.underlyingData();
          }
          return this.__data;
        };
      }
      const defineAttrFloat = (kls, attr) => {
        const desc = kls.__nativeFields__[attr];
        const cacheKey = `_$_${attr}`;
        assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`);
        Object.defineProperty(kls.prototype, desc.fieldName, {
          configurable: true,
          enumerable: true,
          get() {
            if (this[cacheKey] === undefined) {
              this[cacheKey] = new Float32Array(this._arraybuffer(), desc.fieldOffset, 1);
            }
            return this[cacheKey][0];
          },
          set(v) {
            if (this[cacheKey] === undefined) {
              this[cacheKey] = new Float32Array(this._arraybuffer(), desc.fieldOffset, 1);
            }
            this[cacheKey][0] = v;
          }
        });
      };
      const defineAttrInt = (kls, attr) => {
        const desc = kls.__nativeFields__[attr];
        if (!desc) {
          console.error(`attr ${attr} not defined in class ${kls.toString()}`);
        }
        const cacheKey = `_$_${attr}`;
        assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`);
        Object.defineProperty(kls.prototype, desc.fieldName, {
          configurable: true,
          enumerable: true,
          get() {
            if (this[cacheKey] === undefined) {
              this[cacheKey] = new Int32Array(this._arraybuffer(), desc.fieldOffset, 1);
            }
            return this[cacheKey][0];
          },
          set(v) {
            if (this[cacheKey] === undefined) {
              this[cacheKey] = new Int32Array(this._arraybuffer(), desc.fieldOffset, 1);
            }
            this[cacheKey][0] = v;
          }
        });
      };
      {
        cacheProperty(ns.Line, 's');
        cacheProperty(ns.Line, 'e');
        Object.setPrototypeOf(ns.Line.prototype, Line.prototype);
        cacheUnderlyingData(ns.Plane);
        cacheProperty(ns.Plane, 'n');
        defineAttrFloat(ns.Plane, 'd');
        Object.setPrototypeOf(ns.Plane.prototype, Plane.prototype);
        cacheUnderlyingData(ns.Ray);
        cacheProperty(ns.Ray, 'o');
        cacheProperty(ns.Ray, 'd');
        Object.setPrototypeOf(ns.Ray.prototype, Ray.prototype);
        cacheUnderlyingData(ns.Triangle);
        cacheProperty(ns.Triangle, 'a');
        cacheProperty(ns.Triangle, 'b');
        cacheProperty(ns.Triangle, 'c');
        Object.setPrototypeOf(ns.Triangle.prototype, Triangle.prototype);
        cacheUnderlyingData(ns.Sphere);
        cacheProperty(ns.Sphere, '_center');
        defineAttrFloat(ns.Sphere, '_radius');
        Object.setPrototypeOf(ns.Sphere.prototype, Sphere.prototype);
        cacheUnderlyingData(ns.AABB);
        cacheProperty(ns.AABB, 'center');
        cacheProperty(ns.AABB, 'halfExtents');
        Object.setPrototypeOf(ns.AABB.prototype, AABB.prototype);
        cacheUnderlyingData(ns.Capsule);
        defineAttrFloat(ns.Capsule, 'radius');
        defineAttrFloat(ns.Capsule, 'halfHeight');
        defineAttrInt(ns.Capsule, 'axis');
        cacheProperty(ns.Capsule, 'center');
        cacheProperty(ns.Capsule, 'rotation');
        cacheProperty(ns.Capsule, 'ellipseCenter0');
        cacheProperty(ns.Capsule, 'ellipseCenter1');
        Object.setPrototypeOf(ns.Capsule.prototype, Capsule.prototype);
        cacheProperty(ns.Frustum, 'vertices');
        cacheProperty(ns.Frustum, 'planes');
        Object.setPrototypeOf(ns.Frustum.prototype, Frustum.prototype);
        const descOf_type = Object.getOwnPropertyDescriptor(ns.ShapeBase.prototype, '_type');
        for (const kls of [ns.Line, ns.Plane, ns.Ray, ns.Triangle, ns.Sphere, ns.AABB, ns.Capsule, ns.Frustum]) {
          Object.defineProperty(kls.prototype, '_type', descOf_type);
        }
      }

      const ShapeType = {
        "SHAPE_RAY": 1,
        "SHAPE_LINE": 2,
        "SHAPE_SPHERE": 4,
        "SHAPE_AABB": 8,
        "SHAPE_OBB": 16,
        "SHAPE_PLANE": 32,
        "SHAPE_TRIANGLE": 64,
        "SHAPE_FRUSTUM": 128,
        "SHAPE_FRUSTUM_ACCURATE": 256,
        "SHAPE_CAPSULE": 512,
        "SHAPE_SPLINE": 1024
      };

      const _v3_tmp = new Vec3();
      const _v3_tmp2 = new Vec3();
      const _m3_tmp = new Mat3();
      const 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);
      };
      class OBB {
        static 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);
        }
        static 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);
        }
        static copy(out, a) {
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          Mat3.copy(out.orientation, a.orientation);
          return out;
        }
        static 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;
        }
        static 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;
        }
        get type() {
          return this._type;
        }
        constructor(cx = 0, cy = 0, cz = 0, hw = 1, hh = 1, hl = 1, ox_1 = 1, ox_2 = 0, ox_3 = 0, oy_1 = 0, oy_2 = 1, oy_3 = 0, oz_1 = 0, oz_2 = 0, oz_3 = 1) {
          this.center = void 0;
          this.halfExtents = void 0;
          this.orientation = void 0;
          this._type = void 0;
          this._type = 16;
          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);
        }
        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);
        }
        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);
        }
        translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
          Mat3.fromQuat(out.orientation, rot);
        }
        setScale(scale, out) {
          Vec3.multiply(out.halfExtents, this.halfExtents, scale);
        }
      }

      function binarySearch(array, value) {
        return binarySearchEpsilon(array, value, 0);
      }
      function binarySearchEpsilon(array, value, EPSILON = 1e-6) {
        let low = 0;
        let high = array.length - 1;
        let middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          const 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) {
        let low = 0;
        let high = array.length - 1;
        let middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          const 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;
      }

      let _Symbol$iterator$1;
      _Symbol$iterator$1 = Symbol.iterator;
      class KeyframeCurve {
        constructor() {
          this._times = [];
          this._values = [];
        }
        get keyFramesCount() {
          return this._times.length;
        }
        get rangeMin() {
          return this._times[0];
        }
        get rangeMax() {
          return this._times[this._values.length - 1];
        }
        [_Symbol$iterator$1]() {
          let index = 0;
          return {
            next: () => {
              if (index >= this._times.length) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                const value = [this._times[index], this._values[index]];
                ++index;
                return {
                  done: false,
                  value
                };
              }
            }
          };
        }
        keyframes() {
          return this;
        }
        times() {
          return this._times;
        }
        values() {
          return this._values;
        }
        getKeyframeTime(index) {
          return this._times[index];
        }
        getKeyframeValue(index) {
          return this._values[index];
        }
        addKeyFrame(time, keyframeValue) {
          return this._insertNewKeyframe(time, keyframeValue);
        }
        removeKeyframe(index) {
          this._times.splice(index, 1);
          this._values.splice(index, 1);
        }
        indexOfKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        }
        updateTime(index, time) {
          const value = this._values[index];
          this.removeKeyframe(index);
          this._insertNewKeyframe(time, value);
        }
        assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.slice());
          } else {
            const keyframes = Array.from(times);
            this.setKeyframes(keyframes.map(([time]) => time), keyframes.map(([, value]) => value));
          }
        }
        clear() {
          this._times.length = 0;
          this._values.length = 0;
        }
        searchKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        }
        setKeyframes(times, values) {
          assertIsTrue(times.length === values.length);
          assertIsTrue(isSorted(times));
          this._times = times;
          this._values = values;
        }
        _insertNewKeyframe(time, value) {
          const times = this._times;
          const values = this._values;
          const nFrames = times.length;
          const index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return index;
          }
          const 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;
        }
      }
      CCClass.fastDefine('cc.KeyframeCurve', KeyframeCurve, {
        _times: [],
        _values: []
      });
      function isSorted(values) {
        return values.every((value, index, array) => index === 0 || value > array[index - 1] || approx(value, array[index - 1], 1e-6));
      }

      const RealInterpolationMode = exports("RealInterpolationMode", {
        "LINEAR": 0,
        "CONSTANT": 1,
        "CUBIC": 2
      });
      const ExtrapolationMode = exports("ExtrapolationMode", {
        "LINEAR": 0,
        "CLAMP": 1,
        "LOOP": 2,
        "PING_PONG": 3
      });
      const TangentWeightMode = exports("TangentWeightMode", {
        "NONE": 0,
        "LEFT": 1,
        "RIGHT": 2,
        "BOTH": 3
      });

      function solveCubic(coeff0, coeff1, coeff2, coeff3, solutions) {
        const a = coeff2 / coeff3;
        const b = coeff1 / coeff3;
        const c = coeff0 / coeff3;
        const sqrA = a * a;
        const p = 1.0 / 3.0 * (-1.0 / 3 * sqrA + b);
        const q = 1.0 / 2.0 * (2.0 / 27.0 * a * sqrA - 1.0 / 3 * a * b + c);
        const cubicP = p * p * p;
        const d = q * q + cubicP;
        let nSolutions = 0;
        if (isZero(d)) {
          if (isZero(q)) {
            solutions[0] = 0;
            return 1;
          } else {
            const u = Math.cbrt(-q);
            solutions[0] = 2 * u;
            solutions[1] = -u;
            return 2;
          }
        } else if (d < 0) {
          const phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cubicP));
          const 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 {
          const sqrtD = Math.sqrt(d);
          const u = Math.cbrt(sqrtD - q);
          const v = -Math.cbrt(sqrtD + q);
          solutions[0] = u + v;
          nSolutions = 1;
        }
        const sub = 1.0 / 3 * a;
        for (let i = 0; i < nSolutions; ++i) {
          solutions[i] -= sub;
        }
        return nSolutions;
      }
      const 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);
      }

      const emptyDecorator = () => {};
      const emptyDecoratorFn = () => emptyDecorator;
      const emptySmartClassDecorator = makeSmartClassDecorator(() => {});
      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) {
        const cache = getClassCache(constructor);
        if (cache) {
          const proto = getSubDict(cache, 'proto');
          getSubDict(proto, 'editor')[propertyName] = value;
        }
      }
      function makeEditorClassDecoratorFn(propertyName) {
        return value => constructor => {
          writeEditorClassProperty(constructor, propertyName, value);
        };
      }
      const CACHE_KEY = '__ccclassCache__';
      function getClassCache(ctor, decoratorName) {
        return getSubDict(ctor, CACHE_KEY);
      }
      function getSubDict(obj, key) {
        return obj[key] || (obj[key] = {});
      }

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

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

      function property(target, propertyKey, descriptorOrInitializer) {
        let options = null;
        function normalized(target, propertyKey, descriptorOrInitializer) {
          const classStash = getOrCreateClassStash(target);
          const propertyStash = getOrCreateEmptyPropertyStash(target, propertyKey);
          const classConstructor = target.constructor;
          mergePropertyOptions(classStash, propertyStash, classConstructor, propertyKey, options, descriptorOrInitializer);
        }
        if (target === undefined) {
          return property({
            type: undefined
          });
        } else if (typeof propertyKey === 'undefined') {
          options = target;
          return normalized;
        } else {
          normalized(target, propertyKey, descriptorOrInitializer);
          return undefined;
        }
      }
      function getDefaultFromInitializer(initializer) {
        let value;
        try {
          value = initializer();
        } catch (e) {
          return initializer;
        }
        if (typeof value !== 'object' || value === null) {
          return value;
        } else {
          return initializer;
        }
      }
      function extractActualDefaultValues(classConstructor) {
        let dummyObj;
        try {
          dummyObj = new classConstructor();
        } catch (e) {
          return {};
        }
        return dummyObj;
      }
      function getOrCreateClassStash(target) {
        const cache = getClassCache(target.constructor);
        return cache;
      }
      function getOrCreateEmptyPropertyStash(target, propertyKey) {
        var _ref, _properties$_ref;
        const classStash = getClassCache(target.constructor);
        const ccclassProto = getSubDict(classStash, 'proto');
        const properties = getSubDict(ccclassProto, 'properties');
        const 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;
        const classStash = getClassCache(target.constructor);
        const ccclassProto = getSubDict(classStash, 'proto');
        const properties = getSubDict(ccclassProto, 'properties');
        const propertyStash = (_properties$_ref2 = properties[_ref2 = propertyKey]) !== null && _properties$_ref2 !== void 0 ? _properties$_ref2 : properties[_ref2] = {};
        propertyStash.__internalFlags |= 1;
        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) {
        let fullOptions;
        const isGetset = descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set);
        if (options) {
          fullOptions = getFullFormOfProperty(options, isGetset);
        }
        const 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 {
          const actualDefaultValues = classStash.default || (classStash.default = extractActualDefaultValues(classConstructor));
          if (actualDefaultValues.hasOwnProperty(propertyKey)) {
            propertyStash.default = actualDefaultValues[propertyKey];
          }
        }
      }

      const 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] = {};
      }

      const serializable$l = exports("serializable", (target, propertyKey, descriptorOrInitializer) => {
        const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        setImplicitSerializable(propertyStash);
      });
      function formerlySerializedAs$2(name) {
        return (target, propertyKey, descriptorOrInitializer) => {
          const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
          propertyStash.formerlySerializedAs = name;
          setImplicitSerializable(propertyStash);
        };
      }
      const editorOnly = (target, propertyKey, descriptorOrInitializer) => {
        const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.editorOnly = true;
        setImplicitSerializable(propertyStash);
      };
      function setImplicitSerializable(propertyStash) {
        propertyStash.__internalFlags |= 4;
      }
      const uniquelyReferenced = emptyDecorator ;

      const executeInEditMode$2 = emptySmartClassDecorator;
      const menu$f = emptyDecoratorFn;
      const playOnFocus = emptySmartClassDecorator;
      const inspector = emptyDecoratorFn;
      const icon = emptyDecoratorFn;
      const help$3 = emptyDecoratorFn;
      const editable$5 = exports("editable", emptyDecorator );
      const visible$3 = exports("visible", emptyDecoratorFn );
      const readOnly = emptyDecorator ;
      const displayName$2 = exports("displayName", emptyDecoratorFn );
      const tooltip$1 = exports("tooltip", emptyDecoratorFn );
      const range = exports("range", emptyDecoratorFn );
      const rangeMin = emptyDecoratorFn ;
      const rangeStep = exports("rangeStep", emptyDecoratorFn );
      const slide = exports("slide", emptyDecorator );
      const displayOrder$2 = exports("displayOrder", emptyDecoratorFn );
      const disallowAnimation$1 = exports("disallowAnimation", emptyDecorator );

      const integer = type$a(CCInteger);
      const float = type$a(CCFloat);
      const boolean = type$a(CCBoolean);
      const string = type$a(CCString);
      function type$a(type) {
        return property({
          type
        });
      }

      const override$1 = exports("override", (target, propertyKey, descriptorOrInitializer) => {
        const propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.override = true;
      });

      class Empty {}
      const EditorExtendable = exports("EditorExtendable", editorExtendableInternal());
      assertIsTrue(editorExtrasTag === '__editorExtras__', 'editorExtrasTag needs to be updated.');
      function editorExtendableInternal(Base, className) {
        {
          return Empty;
        }
      }

      var _decorator = /*#__PURE__*/Object.freeze({
        __proto__: null,
        boolean: boolean,
        ccclass: ccclass$H,
        disallowAnimation: disallowAnimation$1,
        disallowMultiple: disallowMultiple$1,
        displayName: displayName$2,
        displayOrder: displayOrder$2,
        editable: editable$5,
        executeInEditMode: executeInEditMode$2,
        executionOrder: executionOrder$1,
        float: float,
        formerlySerializedAs: formerlySerializedAs$2,
        help: help$3,
        icon: icon,
        inspector: inspector,
        integer: integer,
        menu: menu$f,
        override: override$1,
        playOnFocus: playOnFocus,
        property: property,
        range: range,
        rangeStep: rangeStep,
        requireComponent: requireComponent,
        serializable: serializable$l,
        slide: slide,
        string: string,
        tooltip: tooltip$1,
        type: type$a,
        uniquelyReferenced: uniquelyReferenced,
        visible: visible$3
      });
      exports("_decorator", _decorator);

      var _dec$2q, _class$2q, _class2$21, _initializer$1U, _initializer2$1r, _initializer3$13, _initializer4$W, _class3$F;
      const StorageUnit = {
        "Uint8": 0,
        "Uint16": 1,
        "Uint32": 2,
        "Int8": 3,
        "Int16": 4,
        "Int32": 5,
        "Float32": 6,
        "Float64": 7
      };
      const ElementType = {
        "Scalar": 0,
        "Vec2": 1,
        "Vec3": 2,
        "Vec4": 3,
        "Quat": 4,
        "Mat4": 5
      };
      const elementTypeBits = 3;
      function combineStorageUnitElementType(unit, elementType) {
        return (elementType << elementTypeBits) + unit;
      }
      function extractStorageUnitElementType(combined) {
        return {
          storageUnit: ~(-1 << elementTypeBits) & combined,
          elementType: combined >> elementTypeBits
        };
      }
      let CompactValueTypeArray = exports("CompactValueTypeArray", (_dec$2q = ccclass$H('cc.CompactValueTypeArray'), _dec$2q(_class$2q = (_class2$21 = (_class3$F = class CompactValueTypeArray {
        constructor() {
          this._byteOffset = _initializer$1U && _initializer$1U();
          this._unitCount = _initializer2$1r && _initializer2$1r();
          this._unitElement = _initializer3$13 && _initializer3$13();
          this._length = _initializer4$W && _initializer4$W();
        }
        static lengthFor(values, elementType, unit) {
          const elementTraits = getElementTraits(elementType);
          return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;
        }
        static compress(values, elementType, unit, arrayBuffer, byteOffset, presumedByteOffset) {
          const elementTraits = getElementTraits(elementType);
          const storageConstructor = getStorageConstructor(unit);
          const unitCount = elementTraits.requiredUnits * values.length;
          const storage = new storageConstructor(arrayBuffer, byteOffset, unitCount);
          for (let i = 0; i < values.length; ++i) {
            elementTraits.compress(storage, i, values[i]);
          }
          const result = new CompactValueTypeArray();
          result._unitElement = combineStorageUnitElementType(unit, elementType);
          result._byteOffset = presumedByteOffset;
          result._unitCount = unitCount;
          result._length = values.length;
          return result;
        }
        decompress(arrayBuffer) {
          const {
            storageUnit,
            elementType
          } = extractStorageUnitElementType(this._unitElement);
          const elementTraits = getElementTraits(elementType);
          const storageConstructor = getStorageConstructor(storageUnit);
          const storage = new storageConstructor(arrayBuffer, this._byteOffset, this._unitCount);
          const result = new Array(this._length);
          for (let i = 0; i < this._length; ++i) {
            result[i] = elementTraits.decompress(storage, i);
          }
          return result;
        }
      }, _class3$F.StorageUnit = StorageUnit, _class3$F.ElementType = ElementType, _class3$F), (_initializer$1U = applyDecoratedInitializer(_class2$21.prototype, "_byteOffset", [serializable$l], function () {
        return 0;
      }), _initializer2$1r = applyDecoratedInitializer(_class2$21.prototype, "_unitCount", [serializable$l], function () {
        return 0;
      }), _initializer3$13 = applyDecoratedInitializer(_class2$21.prototype, "_unitElement", [serializable$l], function () {
        return combineStorageUnitElementType(0, 0);
      }), _initializer4$W = applyDecoratedInitializer(_class2$21.prototype, "_length", [serializable$l], function () {
        return 0;
      })), _class2$21)) || _class$2q));
      function getElementTraits(elementType) {
        return BuiltinElementTypeTraits[elementType];
      }
      function getStorageConstructor(unit) {
        switch (unit) {
          case 0:
            return Uint8Array;
          case 1:
            return Uint16Array;
          case 2:
            return Uint32Array;
          case 3:
            return Int8Array;
          case 4:
            return Int16Array;
          case 5:
            return Int32Array;
          case 6:
            return Float32Array;
          case 7:
            return Float64Array;
        }
      }
      const BuiltinElementTypeTraits = {
        [0]: {
          requiredUnits: 1,
          compress(storage, index, value) {
            storage[index] = value;
          },
          decompress(storage, index) {
            return storage[index];
          }
        },
        [1]: {
          requiredUnits: 2,
          compress(storage, index, value) {
            storage[index * 2] = value.x;
            storage[index * 2 + 1] = value.y;
          },
          decompress(storage, index) {
            return new Vec3(storage[index * 2], storage[index * 2 + 1]);
          }
        },
        [2]: {
          requiredUnits: 3,
          compress(storage, index, value) {
            storage[index * 3] = value.x;
            storage[index * 3 + 1] = value.y;
            storage[index * 3 + 2] = value.z;
          },
          decompress(storage, index) {
            return new Vec3(storage[index * 3], storage[index * 3 + 1], storage[index * 3 + 2]);
          }
        },
        [3]: {
          requiredUnits: 4,
          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(storage, index) {
            return new Vec4(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
          }
        },
        [4]: {
          requiredUnits: 4,
          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(storage, index) {
            return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
          }
        },
        [5]: {
          requiredUnits: 16,
          compress(storage, index, value) {
            Mat4.toArray(storage, value, index * 16);
          },
          decompress(storage, index) {
            return Mat4.fromArray(new Mat4(), storage, index * 16);
          }
        }
      };

      const serializeTag = exports("serializeTag", Symbol('[[Serialize]]'));
      const deserializeTag = exports("deserializeTag", 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 : 1024 ** (k - 1);
      }
      function expoOut(k) {
        return k === 1 ? 1 : 1 - 2 ** (-10 * k);
      }
      function expoInOut(k) {
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        k *= 2;
        if (k < 1) {
          return 0.5 * 1024 ** (k - 1);
        }
        return 0.5 * (-(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) {
        let s;
        let a = 0.1;
        const 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 * 2 ** (10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
      }
      function elasticOut(k) {
        let s;
        let a = 0.1;
        const 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 * 2 ** (-10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
      }
      function elasticInOut(k) {
        let s;
        let a = 0.1;
        const 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 * 2 ** (10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
        }
        return a * 2 ** (-10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
      }
      function backIn(k) {
        if (k === 1) {
          return 1;
        }
        const s = 1.70158;
        return k * k * ((s + 1) * k - s);
      }
      function backOut(k) {
        if (k === 0) {
          return 0;
        }
        const s = 1.70158;
        return --k * k * ((s + 1) * k + s) + 1;
      }
      function backInOut(k) {
        const 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);
      }
      const quadOutIn = _makeOutIn(quadIn, quadOut);
      const cubicOutIn = _makeOutIn(cubicIn, cubicOut);
      const quartOutIn = _makeOutIn(quartIn, quartOut);
      const quintOutIn = _makeOutIn(quintIn, quintOut);
      const sineOutIn = _makeOutIn(sineIn, sineOut);
      const expoOutIn = _makeOutIn(expoIn, expoOut);
      const circOutIn = _makeOutIn(circIn, circOut);
      const elasticOutIn = _makeOutIn(elasticIn, elasticOut);
      const backOutIn = _makeOutIn(backIn, backOut);
      const bounceOutIn = _makeOutIn(bounceIn, bounceOut);
      function _makeOutIn(fnIn, fnOut) {
        return 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,
        backIn: backIn,
        backInOut: backInOut,
        backOut: backOut,
        backOutIn: backOutIn,
        bounceIn: bounceIn,
        bounceInOut: bounceInOut,
        bounceOut: bounceOut,
        bounceOutIn: bounceOutIn,
        circIn: circIn,
        circInOut: circInOut,
        circOut: circOut,
        circOutIn: circOutIn,
        constant: constant,
        cubicIn: cubicIn,
        cubicInOut: cubicInOut,
        cubicOut: cubicOut,
        cubicOutIn: cubicOutIn,
        elasticIn: elasticIn,
        elasticInOut: elasticInOut,
        elasticOut: elasticOut,
        elasticOutIn: elasticOutIn,
        expoIn: expoIn,
        expoInOut: expoInOut,
        expoOut: expoOut,
        expoOutIn: expoOutIn,
        fade: fade,
        linear: linear,
        quadIn: quadIn,
        quadInOut: quadInOut,
        quadOut: quadOut,
        quadOutIn: quadOutIn,
        quartIn: quartIn,
        quartInOut: quartInOut,
        quartOut: quartOut,
        quartOutIn: quartOutIn,
        quintIn: quintIn,
        quintInOut: quintInOut,
        quintOut: quintOut,
        quintOutIn: quintOutIn,
        sineIn: sineIn,
        sineInOut: sineInOut,
        sineOut: sineOut,
        sineOutIn: sineOutIn,
        smooth: smooth
      });
      exports("easing", easing);

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

      const REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START = 0;
      const REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
      const REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START = 8;
      const REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
      const REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START = 16;
      const 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));
      const REAL_KEYFRAME_VALUE_DEFAULT_FLAGS = 0 << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START | 0 << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START | 0 << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
      class RealKeyframeValue extends EditorExtendable {
        constructor() {
          super();
          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;
        }
        get interpolationMode() {
          return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
        }
        set interpolationMode(value) {
          this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK;
          this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
        }
        get tangentWeightMode() {
          return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
        }
        set tangentWeightMode(value) {
          this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK;
          this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
        }
        get easingMethod() {
          return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
        }
        set easingMethod(value) {
          this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK;
          this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
        }
      }
      CCClass.fastDefine('cc.RealKeyframeValue', RealKeyframeValue, {
        interpolationMode: 0,
        tangentWeightMode: 0,
        value: 0.0,
        rightTangent: 0.0,
        rightTangentWeight: 0.0,
        leftTangent: 0.0,
        leftTangentWeight: 0.0,
        easingMethod: 0,
        [editorExtrasTag]: undefined
      });
      CCClass.Attr.setClassAttr(RealKeyframeValue, editorExtrasTag, 'editorOnly', true);
      getOrCreateSerializationMetadata(RealKeyframeValue).uniquelyReferenced = true;
      function createRealKeyframeValue(params) {
        const realKeyframeValue = new RealKeyframeValue();
        if (typeof params === 'number') {
          realKeyframeValue.value = params;
        } else {
          const {
            interpolationMode,
            tangentWeightMode,
            value,
            rightTangent,
            rightTangentWeight,
            leftTangent,
            leftTangentWeight,
            easingMethod,
            [editorExtrasTag]: editorExtras
          } = params;
          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;
      }
      class RealCurve extends KeyframeCurve {
        constructor() {
          super();
          this.preExtrapolation = 1;
          this.postExtrapolation = 1;
        }
        evaluate(time) {
          const {
            _times: times,
            _values: values
          } = this;
          const nFrames = times.length;
          if (nFrames === 0) {
            return 0.0;
          }
          const firstTime = times[0];
          const lastTime = times[nFrames - 1];
          if (time < firstTime) {
            const {
              preExtrapolation
            } = this;
            const preValue = values[0];
            if (preExtrapolation === 1 || nFrames < 2) {
              return preValue.value;
            }
            switch (preExtrapolation) {
              case 0:
                return linearTrend(firstTime, values[0].value, times[1], values[1].value, time);
              case 2:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case 3:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return preValue.value;
            }
          } else if (time > lastTime) {
            const {
              postExtrapolation
            } = this;
            const preFrame = values[nFrames - 1];
            if (postExtrapolation === 1 || nFrames < 2) {
              return preFrame.value;
            }
            switch (postExtrapolation) {
              case 0:
                return linearTrend(lastTime, preFrame.value, times[nFrames - 2], values[nFrames - 2].value, time);
              case 2:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case 3:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return preFrame.value;
            }
          }
          const index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return values[index].value;
          }
          const iNext = ~index;
          {
            assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          }
          const iPre = iNext - 1;
          const preTime = times[iPre];
          const preValue = values[iPre];
          const nextTime = times[iNext];
          const nextValue = values[iNext];
          {
            assertIsTrue(nextTime > time && time > preTime);
          }
          const dt = nextTime - preTime;
          const ratio = (time - preTime) / dt;
          return evalBetweenTwoKeyFrames(preTime, preValue, nextTime, nextValue, ratio);
        }
        addKeyFrame(time, value) {
          return super.addKeyFrame(time, createRealKeyframeValue(value));
        }
        assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(value => createRealKeyframeValue(value)));
          } else {
            const keyframes = Array.from(times);
            this.setKeyframes(keyframes.map(([time]) => time), keyframes.map(([, value]) => createRealKeyframeValue(value)));
          }
        }
        isConstant(tolerance) {
          if (this._values.length <= 1) {
            return true;
          }
          const firstVal = this._values[0].value;
          return this._values.every(frame => approx(frame.value, firstVal, tolerance));
        }
        [serializeTag](output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          const {
            _times: times,
            _values: keyframeValues
          } = this;
          const nKeyframes = times.length;
          const dataSize = 0 + OVERFLOW_BYTES + OVERFLOW_BYTES + FRAME_COUNT_BYTES$1 + TIME_BYTES$1 * nKeyframes + REAL_KEY_FRAME_VALUE_MAX_SIZE * nKeyframes;
          const dataView = new DataView(new ArrayBuffer(dataSize));
          let 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((time, index) => dataView.setFloat32(currentOffset + TIME_BYTES$1 * index, time, true));
          currentOffset += TIME_BYTES$1 * nKeyframes;
          for (const keyframeValue of keyframeValues) {
            currentOffset = saveRealKeyFrameValue(dataView, keyframeValue, currentOffset);
          }
          const bytes = new Uint8Array(dataView.buffer, 0, currentOffset);
          output.writeProperty('bytes', bytes);
          const keyframeValueEditorExtras = keyframeValues.map(keyframeValue => keyframeValue[editorExtrasTag]);
          if (keyframeValueEditorExtras.some(extras => extras !== undefined)) {
            output.writeProperty(`keyframeValueEditorExtras`, keyframeValueEditorExtras);
          }
        }
        [deserializeTag](input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          const bytes = input.readProperty('bytes');
          const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          let currentOffset = 0;
          this.preExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          this.postExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          const nKeyframes = dataView.getUint32(currentOffset, true);
          currentOffset += FRAME_COUNT_BYTES$1;
          const times = Array.from({
            length: nKeyframes
          }, (_, index) => dataView.getFloat32(currentOffset + TIME_BYTES$1 * index, true));
          currentOffset += TIME_BYTES$1 * nKeyframes;
          const keyframeValues = new Array(nKeyframes);
          for (let iKeyFrame = 0; iKeyFrame < nKeyframes; ++iKeyFrame) {
            const keyframeValue = createRealKeyframeValue({});
            currentOffset = loadRealKeyFrameValue(dataView, keyframeValue, currentOffset);
            keyframeValues[iKeyFrame] = keyframeValue;
          }
          assertIsTrue(currentOffset === bytes.byteLength);
          const keyframeValueEditorExtras = input.readProperty(`keyframeValueEditorExtras`);
          if (keyframeValueEditorExtras) {
            assertIsTrue(keyframeValueEditorExtras.length === nKeyframes);
            keyframeValueEditorExtras.forEach((extras, index) => keyframeValues[index][editorExtrasTag] = extras);
          }
          this._times = times;
          this._values = keyframeValues;
        }
      } exports("RealCurve", RealCurve);
      CCClass.fastDefine('cc.RealCurve', RealCurve, {
        _times: [],
        _values: [],
        preExtrapolation: 1,
        postExtrapolation: 1
      });
      const FLAGS_EASING_METHOD_BITS_START = 8;
      const FLAG_EASING_METHOD_MASK = 0xFF << FLAGS_EASING_METHOD_BITS_START;
      const OVERFLOW_BYTES = 1;
      const FRAME_COUNT_BYTES$1 = 4;
      const TIME_BYTES$1 = 4;
      const KEY_FRAME_VALUE_FLAGS_BYTES = 4;
      const VALUE_BYTES$1 = 4;
      const INTERPOLATION_MODE_BYTES$1 = 1;
      const TANGENT_WEIGHT_MODE_BYTES = 1;
      const LEFT_TANGENT_BYTES = 4;
      const LEFT_TANGENT_WEIGHT_BYTES = 4;
      const RIGHT_TANGENT_BYTES = 4;
      const RIGHT_TANGENT_WEIGHT_BYTES = 4;
      const {
        interpolationMode: DEFAULT_INTERPOLATION_MODE,
        tangentWeightMode: DEFAULT_TANGENT_WEIGHT_MODE,
        leftTangent: DEFAULT_LEFT_TANGENT,
        leftTangentWeight: DEFAULT_LEFT_TANGENT_WEIGHT,
        rightTangent: DEFAULT_RIGHT_TANGENT,
        rightTangentWeight: DEFAULT_RIGHT_TANGENT_WEIGHT
      } = createRealKeyframeValue({});
      const 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) {
        let flags = 0;
        let currentOffset = offset;
        const pFlags = currentOffset;
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        const {
          value,
          interpolationMode,
          tangentWeightMode,
          rightTangent,
          rightTangentWeight,
          leftTangent,
          leftTangentWeight,
          easingMethod
        } = keyframeValue;
        dataView.setFloat32(currentOffset, value, true);
        currentOffset += VALUE_BYTES$1;
        if (interpolationMode !== DEFAULT_INTERPOLATION_MODE) {
          flags |= 2;
          dataView.setUint8(currentOffset, interpolationMode);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (tangentWeightMode !== DEFAULT_TANGENT_WEIGHT_MODE) {
          flags |= 4;
          dataView.setUint8(currentOffset, tangentWeightMode);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (leftTangent !== DEFAULT_LEFT_TANGENT) {
          flags |= 8;
          dataView.setFloat32(currentOffset, leftTangent, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (leftTangentWeight !== DEFAULT_LEFT_TANGENT_WEIGHT) {
          flags |= 16;
          dataView.setFloat32(currentOffset, leftTangentWeight, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (rightTangent !== DEFAULT_RIGHT_TANGENT) {
          flags |= 32;
          dataView.setFloat32(currentOffset, rightTangent, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (rightTangentWeight !== DEFAULT_RIGHT_TANGENT_WEIGHT) {
          flags |= 64;
          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) {
        let currentOffset = offset;
        const flags = dataView.getUint32(currentOffset, true);
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        keyframeValue.value = dataView.getFloat32(currentOffset, true);
        currentOffset += VALUE_BYTES$1;
        if (flags & 2) {
          keyframeValue.interpolationMode = dataView.getUint8(currentOffset);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (flags & 4) {
          keyframeValue.tangentWeightMode = dataView.getUint8(currentOffset);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (flags & 8) {
          keyframeValue.leftTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (flags & 16) {
          keyframeValue.leftTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (flags & 32) {
          keyframeValue.rightTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (flags & 64) {
          keyframeValue.rightTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
        }
        const 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) {
        const slope = (nextValue - prevValue) / (nextTime - prevTime);
        return prevValue + (time - prevTime) * slope;
      }
      function evalBetweenTwoKeyFrames(prevTime, prevValue, nextTime, nextValue, ratio) {
        const dt = nextTime - prevTime;
        switch (prevValue.interpolationMode) {
          default:
          case 1:
            return prevValue.value;
          case 0:
            {
              const transformedRatio = prevValue.easingMethod === 0 ? ratio : getEasingFn(prevValue.easingMethod)(ratio);
              return lerp(prevValue.value, nextValue.value, transformedRatio);
            }
          case 2:
            {
              const ONE_THIRD = 1.0 / 3.0;
              const {
                rightTangent: prevTangent,
                rightTangentWeight: prevTangentWeightSpecified
              } = prevValue;
              const prevTangentWeightEnabled = isRightTangentWeightEnabled(prevValue.tangentWeightMode);
              const {
                leftTangent: nextTangent,
                leftTangentWeight: nextTangentWeightSpecified
              } = nextValue;
              const nextTangentWeightEnabled = isLeftTangentWeightEnabled(nextValue.tangentWeightMode);
              if (!prevTangentWeightEnabled && !nextTangentWeightEnabled) {
                const p1 = prevValue.value + ONE_THIRD * prevTangent * dt;
                const p2 = nextValue.value - ONE_THIRD * nextTangent * dt;
                return bezierInterpolate(prevValue.value, p1, p2, nextValue.value, ratio);
              } else {
                let prevTangentWeight = 0.0;
                if (prevTangentWeightEnabled) {
                  prevTangentWeight = prevTangentWeightSpecified;
                } else {
                  const x = dt;
                  const y = dt * prevTangent;
                  prevTangentWeight = Math.sqrt(x * x + y * y) * ONE_THIRD;
                }
                const angle0 = Math.atan(prevTangent);
                const tx0 = Math.cos(angle0) * prevTangentWeight + prevTime;
                const ty0 = Math.sin(angle0) * prevTangentWeight + prevValue.value;
                let nextTangentWeight = 0.0;
                if (nextTangentWeightEnabled) {
                  nextTangentWeight = nextTangentWeightSpecified;
                } else {
                  const x = dt;
                  const y = dt * nextTangent;
                  nextTangentWeight = Math.sqrt(x * x + y * y) * ONE_THIRD;
                }
                const angle1 = Math.atan(nextTangent);
                const tx1 = -Math.cos(angle1) * nextTangentWeight + nextTime;
                const ty1 = -Math.sin(angle1) * nextTangentWeight + nextValue.value;
                const dx = dt;
                const u0x = (tx0 - prevTime) / dx;
                const u1x = (tx1 - prevTime) / dx;
                const u0y = ty0;
                const u1y = ty1;
                const coeff0 = 0.0;
                const coeff1 = 3.0 * u0x;
                const coeff2 = 3.0 * u1x - 6.0 * u0x;
                const coeff3 = 3.0 * (u0x - u1x) + 1.0;
                const solutions = [0.0, 0.0, 0.0];
                const nSolutions = solveCubic(coeff0 - ratio, coeff1, coeff2, coeff3, solutions);
                const param = getParamFromCubicSolution(solutions, nSolutions, ratio);
                const y = bezierInterpolate(prevValue.value, u0y, u1y, nextValue.value, param);
                return y;
              }
            }
        }
      }
      function isLeftTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & 1) !== 0;
      }
      function isRightTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & 2) !== 0;
      }
      function bezierInterpolate(p0, p1, p2, p3, t) {
        const u = 1 - t;
        const coeff0 = u * u * u;
        const coeff1 = 3 * u * u * t;
        const coeff2 = 3 * u * t * t;
        const coeff3 = t * t * t;
        return coeff0 * p0 + coeff1 * p1 + coeff2 * p2 + coeff3 * p3;
      }
      function getParamFromCubicSolution(solutions, solutionsCount, x) {
        let param = x;
        if (solutionsCount === 1) {
          param = solutions[0];
        } else {
          param = -Infinity;
          for (let iSolution = 0; iSolution < solutionsCount; ++iSolution) {
            const 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$1(C1, C2, C3, C4, t) {
        const t1 = 1 - t;
        return t1 * (t1 * (C1 + (C2 * 3 - C1) * t) + C3 * 3 * t * t) + C4 * t * t * t;
      }
      legacyCC.bezier = bezier$1;
      const cos$2 = Math.cos;
      const acos$1 = Math.acos;
      const max$2 = Math.max;
      const pi = Math.PI;
      const tau = 2 * pi;
      const 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) {
        const pa = x - 0;
        const pb = x - curve[0];
        const pc = x - curve[2];
        const pd = x - 1;
        const pa3 = pa * 3;
        const pb3 = pb * 3;
        const pc3 = pc * 3;
        const d = -pa + pb3 - pc3 + pd;
        const rd = 1 / d;
        const r3 = 1 / 3;
        const a = (pa3 - 6 * pb + pc3) * rd;
        const a3 = a * r3;
        const b = (-pa3 + pb3) * rd;
        const c = pa * rd;
        const p = (3 * b - a * a) * r3;
        const p3 = p * r3;
        const q = (2 * a * a * a - 9 * a * b + 27 * c) / 27;
        const q2 = q / 2;
        const discriminant = q2 * q2 + p3 * p3 * p3;
        let u1;
        let v1;
        let x1;
        let x2;
        let x3;
        if (discriminant < 0) {
          const mp3 = -p * r3;
          const mp33 = mp3 * mp3 * mp3;
          const r = sqrt(mp33);
          const t = -q / (2 * r);
          const cosphi = t < -1 ? -1 : t > 1 ? 1 : t;
          const phi = acos$1(cosphi);
          const crtr = crt(r);
          const 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 {
          const sd = sqrt(discriminant);
          u1 = crt(-q2 + sd);
          v1 = crt(q2 + sd);
          x1 = u1 - v1 - a3;
          return x1;
        }
      }
      function bezierByTime(controlPoints, x) {
        const percent = cardano(controlPoints, x);
        const p1y = controlPoints[1];
        const p2y = controlPoints[3];
        return ((1 - percent) * (p1y + (p2y - p1y) * percent) * 3 + percent * percent) * percent;
      }
      legacyCC.bezierByTime = bezierByTime;

      var _dec$2p, _class$2p, _class2$20, _initializer$1T, _initializer2$1q, _initializer3$12, _dec2$1C, _class4$r, _class5$p, _initializer4$V, _initializer5$H;
      const QuatInterpolationMode = exports("QuatInterpolationMode", {
        "SLERP": 0,
        "CONSTANT": 1
      });
      let QuatKeyframeValue = (_dec$2p = ccclass$H('cc.QuatKeyframeValue'), _dec$2p(_class$2p = uniquelyReferenced(_class$2p = (_class2$20 = class QuatKeyframeValue {
        constructor({
          value,
          interpolationMode,
          easingMethod
        } = {}) {
          this.interpolationMode = _initializer$1T && _initializer$1T();
          this.value = _initializer2$1q && _initializer2$1q();
          this.easingMethod = _initializer3$12 && _initializer3$12();
          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$1T = applyDecoratedInitializer(_class2$20.prototype, "interpolationMode", [serializable$l], function () {
        return 0;
      }), _initializer2$1q = applyDecoratedInitializer(_class2$20.prototype, "value", [serializable$l], function () {
        return Quat.clone(Quat.IDENTITY);
      }), _initializer3$12 = applyDecoratedInitializer(_class2$20.prototype, "easingMethod", [serializable$l], function () {
        return 0;
      })), _class2$20)) || _class$2p) || _class$2p);
      function createQuatKeyframeValue(params) {
        return new QuatKeyframeValue(params);
      }
      let QuatCurve = exports("QuatCurve", (_dec2$1C = ccclass$H('cc.QuatCurve'), _dec2$1C(_class4$r = (_class5$p = class QuatCurve extends KeyframeCurve {
        constructor() {
          super();
          this.preExtrapolation = _initializer4$V && _initializer4$V();
          this.postExtrapolation = _initializer5$H && _initializer5$H();
        }
        evaluate(time, quat) {
          var _quat;
          (_quat = quat) !== null && _quat !== void 0 ? _quat : quat = new Quat();
          const {
            _times: times,
            _values: values,
            postExtrapolation,
            preExtrapolation
          } = this;
          const nFrames = times.length;
          if (nFrames === 0) {
            return quat;
          }
          const firstTime = times[0];
          const lastTime = times[nFrames - 1];
          if (time < firstTime) {
            const preValue = values[0];
            switch (preExtrapolation) {
              case 2:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case 3:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case 1:
              default:
                return Quat.copy(quat, preValue.value);
            }
          } else if (time > lastTime) {
            const preValue = values[nFrames - 1];
            switch (postExtrapolation) {
              case 2:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case 3:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case 1:
              default:
                return Quat.copy(quat, preValue.value);
            }
          }
          const index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return Quat.copy(quat, values[index].value);
          }
          const iNext = ~index;
          assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          const iPre = iNext - 1;
          const preTime = times[iPre];
          const preValue = values[iPre];
          const nextTime = times[iNext];
          const nextValue = values[iNext];
          assertIsTrue(nextTime > time && time > preTime);
          const dt = nextTime - preTime;
          const ratio = (time - preTime) / dt;
          switch (preValue.interpolationMode) {
            default:
            case 1:
              return Quat.copy(quat, preValue.value);
            case 0:
              {
                const {
                  easingMethod
                } = preValue;
                const transformedRatio = easingMethod === 0 ? ratio : Array.isArray(easingMethod) ? bezierByTime(easingMethod, ratio) : getEasingFn(easingMethod)(ratio);
                return Quat.slerp(quat, preValue.value, nextValue.value, transformedRatio);
              }
          }
        }
        addKeyFrame(time, value) {
          const keyframeValue = new QuatKeyframeValue(value);
          return super.addKeyFrame(time, keyframeValue);
        }
        assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(value => createQuatKeyframeValue(value)));
          } else {
            const keyframes = Array.from(times);
            this.setKeyframes(keyframes.map(([time]) => time), keyframes.map(([, value]) => createQuatKeyframeValue(value)));
          }
        }
        [serializeTag](output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          const {
            _times: times,
            _values: keyframeValues
          } = this;
          let interpolationModeRepeated = true;
          keyframeValues.forEach((keyframeValue, _index, [firstKeyframeValue]) => {
            if (interpolationModeRepeated && keyframeValue.interpolationMode !== firstKeyframeValue.interpolationMode) {
              interpolationModeRepeated = false;
            }
          });
          const nKeyframes = times.length;
          const nFrames = nKeyframes;
          const interpolationModesSize = INTERPOLATION_MODE_BYTES * (interpolationModeRepeated ? 1 : nFrames);
          const easingMethodsSize = keyframeValues.reduce((result, {
            easingMethod
          }) => result += Array.isArray(easingMethod) ? EASING_METHOD_BYTES + EASING_METHOD_BEZIER_COMPONENT_BYTES * 4 : EASING_METHOD_BYTES, 0);
          let dataSize = 0;
          dataSize += FLAGS_BYTES + FRAME_COUNT_BYTES + TIME_BYTES * nFrames + VALUE_BYTES * 4 * nFrames + easingMethodsSize + interpolationModesSize + 0;
          const dataView = new DataView(new ArrayBuffer(dataSize));
          let P = 0;
          let flags = 0;
          if (interpolationModeRepeated) {
            flags |= 1;
          }
          dataView.setUint32(P, flags, true);
          P += FLAGS_BYTES;
          dataView.setUint32(P, nFrames, true);
          P += FRAME_COUNT_BYTES;
          times.forEach((time, index) => dataView.setFloat32(P + TIME_BYTES * index, time, true));
          P += TIME_BYTES * nFrames;
          keyframeValues.forEach(({
            value: {
              x,
              y,
              z,
              w
            }
          }, index) => {
            const 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(({
            easingMethod
          }, index) => {
            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;
            }
          });
          const INTERPOLATION_MODES_START = P;
          P += interpolationModesSize;
          let pInterpolationMode = INTERPOLATION_MODES_START;
          keyframeValues.forEach(({
            interpolationMode
          }) => {
            dataView.setUint8(pInterpolationMode, interpolationMode);
            if (!interpolationModeRepeated) {
              pInterpolationMode += INTERPOLATION_MODE_BYTES;
            }
          });
          const bytes = new Uint8Array(dataView.buffer);
          output.writeProperty('bytes', bytes);
        }
        [deserializeTag](input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          const bytes = input.readProperty('bytes');
          const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          let P = 0;
          const flags = dataView.getUint32(P, true);
          P += FLAGS_BYTES;
          const interpolationModeRepeated = flags & 1;
          const nFrames = dataView.getUint32(P, true);
          P += FRAME_COUNT_BYTES;
          const times = Array.from({
            length: nFrames
          }, (_, index) => dataView.getFloat32(P + TIME_BYTES * index, true));
          P += TIME_BYTES * nFrames;
          const P_VALUES = P;
          P += VALUE_BYTES * 4 * nFrames;
          const keyframeValues = Array.from({
            length: nFrames
          }, (_, index) => {
            const pQuat = P_VALUES + VALUE_BYTES * 4 * index;
            const x = dataView.getFloat32(pQuat + VALUE_BYTES * 0, true);
            const y = dataView.getFloat32(pQuat + VALUE_BYTES * 1, true);
            const z = dataView.getFloat32(pQuat + VALUE_BYTES * 2, true);
            const w = dataView.getFloat32(pQuat + VALUE_BYTES * 3, true);
            const easingMethod = dataView.getUint8(P);
            ++P;
            const keyframeValue = createQuatKeyframeValue({
              value: {
                x,
                y,
                z,
                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) {
            const interpolationMode = dataView.getUint8(P);
            ++P;
            for (let iKeyframe = 0; iKeyframe < nFrames; ++iKeyframe) {
              keyframeValues[iKeyframe].interpolationMode = interpolationMode;
            }
          } else {
            for (let iKeyframe = 0; iKeyframe < nFrames; ++iKeyframe) {
              const interpolationMode = dataView.getUint8(P + iKeyframe);
              keyframeValues[iKeyframe].interpolationMode = interpolationMode;
            }
            P += nFrames;
          }
          this._times = times;
          this._values = keyframeValues;
        }
      }, (_initializer4$V = applyDecoratedInitializer(_class5$p.prototype, "preExtrapolation", [serializable$l], function () {
        return 1;
      }), _initializer5$H = applyDecoratedInitializer(_class5$p.prototype, "postExtrapolation", [serializable$l], function () {
        return 1;
      })), _class5$p)) || _class4$r));
      const FLAGS_BYTES = 1;
      const FRAME_COUNT_BYTES = 4;
      const TIME_BYTES = 4;
      const VALUE_BYTES = 4;
      const INTERPOLATION_MODE_BYTES = 1;
      const EASING_METHOD_BYTES = 1;
      const EASING_METHOD_BEZIER_TAG = 255;
      const EASING_METHOD_BEZIER_COMPONENT_BYTES = 4;

      var _dec$2o, _class$2o;
      let ObjectCurve = exports("ObjectCurve", (_dec$2o = ccclass$H('cc.ObjectCurve'), _dec$2o(_class$2o = class ObjectCurve extends KeyframeCurve {
        evaluate(time) {
          const iSearch = this.searchKeyframe(time);
          if (iSearch >= 0) {
            return this._values[iSearch];
          }
          const iPrev = clamp$1(~iSearch - 1, 0, this._values.length - 1);
          return this._values[iPrev];
        }
      }) || _class$2o));

      const Mode$1 = Enum({
        Blend: 0,
        Fixed: 1
      });
      class ColorKey {
        constructor() {
          this.color = Color$1.WHITE.clone();
          this.time = 0;
        }
      } exports("ColorKey", ColorKey);
      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);
      class AlphaKey {
        constructor() {
          this.alpha = 1;
          this.time = 0;
        }
      } exports("AlphaKey", AlphaKey);
      CCClass.fastDefine('cc.AlphaKey', AlphaKey, {
        alpha: 1,
        time: 0
      });
      CCClass.Attr.setClassAttr(AlphaKey, 'alpha', 'visible', true);
      CCClass.Attr.setClassAttr(AlphaKey, 'time', 'visible', true);
      class Gradient {
        constructor() {
          this.colorKeys = [];
          this.alphaKeys = [];
          this.mode = Mode$1.Blend;
        }
        setKeys(colorKeys, alphaKeys) {
          this.colorKeys = colorKeys;
          this.alphaKeys = alphaKeys;
        }
        sortKeys() {
          if (this.colorKeys.length > 1) {
            this.colorKeys.sort((a, b) => a.time - b.time);
          }
          if (this.alphaKeys.length > 1) {
            this.alphaKeys.sort((a, b) => a.time - b.time);
          }
        }
        evaluate(time) {
          return this.evaluateFast(new Color$1(), time);
        }
        evaluateFast(out, time) {
          this.getRGB(out, time);
          out.a = this.getAlpha(time);
          return out;
        }
        randomColor() {
          return this.getRandomColor(new Color$1());
        }
        getRandomColor(out) {
          const c = this.colorKeys[Math.trunc(random() * this.colorKeys.length)];
          const a = this.alphaKeys[Math.trunc(random() * this.alphaKeys.length)];
          out.set(c.color);
          out.a = a.alpha;
          return out;
        }
        getRGB(out, time) {
          const colorKeys = this.colorKeys;
          const length = colorKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$2);
            for (let i = 1; i < length; ++i) {
              const preTime = colorKeys[i - 1].time;
              const curTime = colorKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$1.Fixed) {
                  Color$1.copy(out, colorKeys[i].color);
                  return out;
                }
                const factor = (time - preTime) / (curTime - preTime);
                Color$1.lerp(out, colorKeys[i - 1].color, colorKeys[i].color, factor);
                return out;
              }
            }
            const lastIndex = length - 1;
            if (approx(time, colorKeys[lastIndex].time, EPSILON$2)) {
              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;
        }
        getAlpha(time) {
          const basicAlpha = 0;
          const alphaKeys = this.alphaKeys;
          const length = alphaKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$2);
            for (let i = 1; i < length; ++i) {
              const preTime = alphaKeys[i - 1].time;
              const curTime = alphaKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$1.Fixed) {
                  return alphaKeys[i].alpha;
                }
                const factor = (time - preTime) / (curTime - preTime);
                return lerp(alphaKeys[i - 1].alpha, alphaKeys[i].alpha, factor);
              }
            }
            const lastIndex = length - 1;
            if (approx(time, alphaKeys[lastIndex].time, EPSILON$2)) {
              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;
          }
        }
      } exports("Gradient", 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);

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

      const SplineMode = {
        "LINEAR": 0,
        "BEZIER": 1,
        "CATMULL_ROM": 2
      };
      const SPLINE_WHOLE_INDEX = 0xffffffff;
      const _v0 = new Vec3();
      const _v1 = new Vec3();
      const _v2 = new Vec3();
      const _v3 = new Vec3();
      class Spline {
        constructor(mode = 2, knots = []) {
          this._type = void 0;
          this._knots = [];
          this._type = 1024;
          this._mode = mode;
          for (let i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        }
        static create(mode, knots = []) {
          return new Spline(mode, knots);
        }
        static clone(s) {
          return new Spline(s.mode, s.knots);
        }
        static copy(out, s) {
          out._mode = s.mode;
          out._knots.length = 0;
          const knots = s.knots;
          const length = knots.length;
          for (let i = 0; i < length; i++) {
            out._knots[i] = new Vec3(knots[i]);
          }
          return out;
        }
        get type() {
          return this._type;
        }
        get mode() {
          return this._mode;
        }
        get knots() {
          return this._knots;
        }
        setModeAndKnots(mode, knots) {
          this._mode = mode;
          this._knots.length = 0;
          for (let i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        }
        clearKnots() {
          this._knots.length = 0;
        }
        getKnotCount() {
          return this._knots.length;
        }
        addKnot(knot) {
          this._knots.push(new Vec3(knot));
        }
        insertKnot(index, knot) {
          const item = new Vec3(knot);
          if (index >= this._knots.length) {
            this._knots.push(item);
            return;
          }
          this._knots.splice(index, 0, item);
        }
        removeKnot(index) {
          assertsArrayIndex(this._knots, index);
          this._knots.splice(index, 1);
        }
        setKnot(index, knot) {
          assertsArrayIndex(this._knots, index);
          this._knots[index].set(knot);
        }
        getKnot(index) {
          assertsArrayIndex(this._knots, index);
          return this._knots[index];
        }
        getPoint(t, index = SPLINE_WHOLE_INDEX) {
          t = clamp$1(t, 0.0, 1.0);
          const segments = this.getSegments();
          if (segments === 0) {
            return new Vec3();
          }
          if (index === SPLINE_WHOLE_INDEX) {
            const deltaT = 1.0 / segments;
            index = Math.floor(t / deltaT);
            t = t % deltaT / deltaT;
          }
          const knots = this._knots;
          if (index >= segments) {
            return new Vec3(knots[knots.length - 1]);
          }
          switch (this._mode) {
            case 0:
              return Spline.calcLinear(knots[index], knots[index + 1], t);
            case 1:
              {
                const start = index * 4;
                return Spline.calcBezier(knots[start], knots[start + 1], knots[start + 2], knots[start + 3], t);
              }
            case 2:
              {
                const v0 = index > 0 ? knots[index - 1] : knots[index];
                const v3 = index + 2 < knots.length ? knots[index + 2] : knots[index + 1];
                return Spline.calcCatmullRom(v0, knots[index], knots[index + 1], v3, t);
              }
            default:
              return new Vec3();
          }
        }
        getPoints(num, index = SPLINE_WHOLE_INDEX) {
          if (num === 0) {
            return [];
          }
          if (num === 1) {
            const point = this.getPoint(0.0, index);
            return [point];
          }
          const points = [];
          const deltaT = 1.0 / (num - 1.0);
          for (let i = 0; i < num; i++) {
            const t = i * deltaT;
            const point = this.getPoint(t, index);
            points.push(point);
          }
          return points;
        }
        getSegments() {
          const count = this._knots.length;
          switch (this._mode) {
            case 0:
            case 2:
              if (count < 2) {
                warnID(14300);
                return 0;
              }
              return count - 1;
            case 1:
              if (count < 4 || count % 4 !== 0) {
                warnID(14301);
                return 0;
              }
              return count / 4;
            default:
              assertID(false, 16407);
              return 0;
          }
        }
        static calcLinear(v0, v1, t) {
          const result = new Vec3();
          Vec3.multiplyScalar(_v0, v0, 1.0 - t);
          Vec3.multiplyScalar(_v1, v1, t);
          Vec3.add(result, _v0, _v1);
          return result;
        }
        static calcBezier(v0, v1, v2, v3, t) {
          const result = new Vec3();
          const 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, v3, t * t * t);
          Vec3.add(_v0, _v0, _v1);
          Vec3.add(_v2, _v2, _v3);
          Vec3.add(result, _v0, _v2);
          return result;
        }
        static calcCatmullRom(v0, v1, v2, v3, t) {
          const result = new Vec3();
          const t2 = t * t;
          const 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, v3, 0.5 * t3 - 0.5 * t2);
          Vec3.add(_v0, _v0, _v1);
          Vec3.add(_v2, _v2, _v3);
          Vec3.add(result, _v0, _v2);
          return result;
        }
      }

      const ERaycastMode = {
        "ALL": 0,
        "CLOSEST": 1,
        "ANY": 2
      };

      replaceProperty(intersect, 'intersect', [{
        name: 'ray_aabb',
        newName: 'rayAABB'
      }, {
        name: 'ray_plane',
        newName: 'rayPlane'
      }, {
        name: 'ray_triangle',
        newName: 'rayTriangle'
      }, {
        name: 'ray_sphere',
        newName: 'raySphere'
      }, {
        name: 'ray_obb',
        newName: 'rayOBB'
      }, {
        name: 'ray_capsule',
        newName: 'rayCapsule'
      }, {
        name: 'ray_subMesh',
        newName: 'raySubMesh'
      }, {
        name: 'ray_mesh',
        newName: 'rayMesh'
      }, {
        name: 'ray_model',
        newName: 'rayModel'
      }, {
        name: 'line_plane',
        newName: 'linePlane'
      }, {
        name: 'line_triangle',
        newName: 'lineTriangle'
      }, {
        name: 'line_aabb',
        newName: 'lineAABB'
      }, {
        name: 'line_obb',
        newName: 'lineOBB'
      }, {
        name: 'line_sphere',
        newName: 'lineSphere'
      }, {
        name: 'aabb_aabb',
        newName: 'aabbWithAABB'
      }, {
        name: 'aabb_obb',
        newName: 'aabbWithOBB'
      }, {
        name: 'aabb_plane',
        newName: 'aabbPlane'
      }, {
        name: 'aabb_frustum',
        newName: 'aabbFrustum'
      }, {
        name: 'aabbFrustum_accurate',
        newName: 'aabbFrustumAccurate'
      }, {
        name: 'obb_point',
        newName: 'obbPoint'
      }, {
        name: 'obb_plane',
        newName: 'obbPlane'
      }, {
        name: 'obb_frustum',
        newName: 'obbFrustum'
      }, {
        name: 'obbFrustum_accurate',
        newName: 'obbFrustumAccurate'
      }, {
        name: 'obb_obb',
        newName: 'obbWithOBB'
      }, {
        name: 'obb_capsule',
        newName: 'obbCapsule'
      }, {
        name: 'sphere_plane',
        newName: 'spherePlane'
      }, {
        name: 'sphere_frustum',
        newName: 'sphereFrustum'
      }, {
        name: 'sphereFrustum_accurate',
        newName: 'sphereFrustumAccurate'
      }, {
        name: 'sphere_sphere',
        newName: 'sphereWithSphere'
      }, {
        name: 'sphere_aabb',
        newName: 'sphereAABB'
      }, {
        name: 'sphere_obb',
        newName: 'sphereOBB'
      }, {
        name: 'sphere_capsule',
        newName: 'sphereCapsule'
      }, {
        name: 'capsule_capsule',
        newName: 'capsuleWithCapsule'
      }]);
      function deprecatedClassMessage(oldClassName, newClassName) {
        warn(`${oldClassName} is deprecated, please use ${newClassName} instead.`);
      }
      class line extends Line {
        constructor() {
          super();
          deprecatedClassMessage('line', 'Line');
        }
      }
      class plane extends Plane {
        constructor() {
          super();
          deprecatedClassMessage('plane', 'Plane');
        }
      }
      class ray extends Ray {
        constructor() {
          super();
          deprecatedClassMessage('ray', 'Ray');
        }
      }
      class triangle extends Triangle {
        constructor() {
          super();
          deprecatedClassMessage('triangle', 'Triangle');
        }
      }
      class sphere extends Sphere {
        constructor() {
          super();
          deprecatedClassMessage('sphere', 'Sphere');
        }
      }
      class aabb extends AABB {
        constructor() {
          super();
          deprecatedClassMessage('aabb', 'AABB');
        }
      }
      class obb extends OBB {
        constructor() {
          super();
          deprecatedClassMessage('obb', 'OBB');
        }
      }
      class capsule extends Capsule {
        constructor() {
          super();
          deprecatedClassMessage('capsule', 'Capsule');
        }
      }
      class frustum extends Frustum {
        constructor() {
          super();
          deprecatedClassMessage('frustum', 'Frustum');
        }
      }

      var geometry = /*#__PURE__*/Object.freeze({
        __proto__: null,
        AABB: AABB,
        AnimationCurve: AnimationCurve,
        Capsule: Capsule,
        ERaycastMode: ERaycastMode,
        Frustum: Frustum,
        Keyframe: Keyframe,
        Line: Line,
        OBB: OBB,
        OptimizedKey: OptimizedKey,
        Plane: Plane,
        Ray: Ray,
        Sphere: Sphere,
        Spline: Spline,
        SplineMode: SplineMode,
        Triangle: Triangle,
        WrapModeMask: WrapModeMask,
        aabb: aabb,
        capsule: capsule,
        constructLegacyCurveAndConvert: constructLegacyCurveAndConvert,
        distance: distance,
        enums: ShapeType,
        evalOptCurve: evalOptCurve,
        frustum: frustum,
        intersect: intersect,
        line: line,
        obb: obb,
        plane: plane,
        ray: ray,
        sphere: sphere,
        triangle: triangle
      });
      exports("geometry", geometry);

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

      const MAX_POOL_SIZE$1 = 20;
      const idGenerator$1 = new IDGenerator('Scheduler');
      class ListEntry {
        static get(target, priority, paused, markedForDeletion) {
          let 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;
        }
        static put(entry) {
          if (ListEntry._listEntries.length < MAX_POOL_SIZE$1) {
            entry.target = null;
            ListEntry._listEntries.push(entry);
          }
        }
        constructor(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;
        }
      }
      ListEntry._listEntries = [];
      class HashUpdateEntry {
        static get(list, entry, target, callback) {
          let 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;
        }
        static put(entry) {
          if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE$1) {
            entry.list = entry.entry = entry.target = entry.callback = null;
            HashUpdateEntry._hashUpdateEntries.push(entry);
          }
        }
        constructor(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;
        }
      }
      HashUpdateEntry._hashUpdateEntries = [];
      class HashTimerEntry {
        static get(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
          let 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;
        }
        static put(entry) {
          if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE$1) {
            entry.timers = entry.target = entry.currentTimer = null;
            HashTimerEntry._hashTimerEntries.push(entry);
          }
        }
        constructor(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;
        }
      }
      HashTimerEntry._hashTimerEntries = [];
      class CallbackTimer {
        static get() {
          return CallbackTimer._timers.pop() || new CallbackTimer();
        }
        static put(timer) {
          if (CallbackTimer._timers.length < MAX_POOL_SIZE$1 && !timer._lock) {
            timer._scheduler = timer._target = timer._callback = null;
            CallbackTimer._timers.push(timer);
          }
        }
        constructor() {
          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;
        }
        initWithCallback(scheduler, callback, target, seconds, repeat, delay) {
          this._lock = false;
          this._scheduler = scheduler;
          this._target = target;
          this._callback = callback;
          this._timesExecuted = 0;
          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;
        }
        getInterval() {
          return this._interval;
        }
        setInterval(interval) {
          this._interval = interval;
        }
        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();
              }
            }
          }
        }
        getCallback() {
          return this._callback;
        }
        trigger() {
          if (this._target && this._callback) {
            this._lock = true;
            this._callback.call(this._target, this._elapsed);
            this._lock = false;
          }
        }
        cancel() {
          if (this._scheduler && this._callback && this._target) {
            this._scheduler.unscheduleForTimer(this, this._target);
          }
        }
      }
      CallbackTimer._timers = [];
      class Scheduler extends System {
        static enableForTarget(target) {
          let found = false;
          if (target.uuid) {
            found = true;
          } else if (target.id) {
            found = true;
          }
          if (!found) {
            target.id = idGenerator$1.getNewId();
          }
        }
        constructor() {
          super();
          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 = [];
        }
        setTimeScale(timeScale) {
          this._timeScale = timeScale;
        }
        getTimeScale() {
          return this._timeScale;
        }
        update(dt) {
          this._updateHashLocked = true;
          if (this._timeScale !== 1) {
            dt *= this._timeScale;
          }
          let i;
          let list;
          let len;
          let 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);
            }
          }
          let elt;
          const 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;
        }
        schedule(callbackTmp, targetTmp, interval, repeat, delay, paused) {
          var _repeat, _delay;
          let callback;
          let 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);
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          let 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);
          }
          let timer;
          let 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;
          }
        }
        scheduleUpdate(target, priority, paused) {
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const 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;
            }
          }
          const listElement = ListEntry.get(target, priority, paused, false);
          let 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);
        }
        unschedule(callback, target) {
          if (!target || !callback) {
            return;
          }
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const element = this._hashForTimers[targetId];
          if (element) {
            const timers = element.timers;
            if (!timers) {
              return;
            }
            for (let i = 0, li = timers.length; i < li; i++) {
              const 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;
              }
            }
          }
        }
        unscheduleForTimer(timerToUnschedule, target) {
          const targetId = target.uuid || target.id;
          const element = this._hashForTimers[targetId];
          const timers = element.timers;
          if (!timers || timers.length === 0) {
            return;
          }
          for (let i = timers.length - 1; i >= 0; i--) {
            const timer = timers[i];
            if (timer === timerToUnschedule) {
              timers.splice(i, 1);
              CallbackTimer.put(timer);
              if (element.timerIndex >= i) {
                element.timerIndex--;
              }
              if (timers.length === 0) {
                this._currentTargetSalvaged = true;
              }
              return;
            }
          }
        }
        unscheduleUpdate(target) {
          if (!target) {
            return;
          }
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const element = this._hashForUpdates[targetId];
          if (element !== null && element !== void 0 && element.entry) {
            if (this._updateHashLocked) {
              element.entry.markedForDeletion = true;
            } else {
              this._removeUpdateFromHash(element.entry);
            }
          }
        }
        unscheduleAllForTarget(target) {
          if (!target) {
            return;
          }
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const element = this._hashForTimers[targetId];
          if (element !== null && element !== void 0 && element.timers) {
            const timers = element.timers;
            if (element.currentTimer && timers.indexOf(element.currentTimer) > -1 && !element.currentTimerSalvaged) {
              element.currentTimerSalvaged = true;
            }
            for (let 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);
        }
        unscheduleAll() {
          this.unscheduleAllWithMinPriority(System.Priority.SCHEDULER);
        }
        unscheduleAllWithMinPriority(minPriority) {
          let i;
          let element;
          const arr = this._arrayForTimers;
          for (i = arr.length - 1; i >= 0; i--) {
            element = arr[i];
            if (element.target) {
              this.unscheduleAllForTarget(element.target);
            }
          }
          let entry;
          let 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++;
            }
          }
        }
        isScheduled(callback, target) {
          assertID(Boolean(callback), 1508);
          assertID(Boolean(target), 1509);
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          const element = this._hashForTimers[targetId];
          if (!element) {
            return false;
          }
          if (element.timers == null) {
            return false;
          } else {
            const timers = element.timers;
            for (let i = 0; i < timers.length; ++i) {
              const timer = timers[i];
              if (callback === timer.getCallback()) {
                return true;
              }
            }
            return false;
          }
        }
        pauseAllTargets() {
          return this.pauseAllTargetsWithMinPriority(System.Priority.SCHEDULER);
        }
        pauseAllTargetsWithMinPriority(minPriority) {
          const idsWithSelectors = [];
          let element;
          const locArrayForTimers = this._arrayForTimers;
          let i;
          let 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);
            }
          }
          let 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;
        }
        resumeTargets(targetsToResume) {
          if (!targetsToResume) {
            return;
          }
          for (let i = 0; i < targetsToResume.length; i++) {
            this.resumeTarget(targetsToResume[i]);
          }
        }
        pauseTarget(target) {
          assertID(Boolean(target), 1503);
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const element = this._hashForTimers[targetId];
          if (element) {
            element.paused = true;
          }
          const elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = true;
          }
        }
        resumeTarget(target) {
          assertID(Boolean(target), 1504);
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          const element = this._hashForTimers[targetId];
          if (element) {
            element.paused = false;
          }
          const elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = false;
          }
        }
        isTargetPaused(target) {
          assertID(Boolean(target), 1505);
          const targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          const element = this._hashForTimers[targetId];
          if (element) {
            return element.paused;
          }
          const elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            return elementUpdate.entry.paused;
          }
          return false;
        }
        _removeHashElement(element) {
          if (!element.target) {
            return;
          }
          const targetId = element.target.uuid || element.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          delete this._hashForTimers[targetId];
          const arr = this._arrayForTimers;
          for (let i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === element) {
              arr.splice(i, 1);
              break;
            }
          }
          HashTimerEntry.put(element);
        }
        _removeUpdateFromHash(entry) {
          if (!entry.target) {
            return;
          }
          const targetId = entry.target.uuid || entry.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          const element = this._hashForUpdates[targetId];
          if (element) {
            const list = element.list;
            const listEntry = element.entry;
            if (list) {
              for (let 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);
          }
        }
        _priorityIn(ppList, listElement, priority) {
          for (let i = 0; i < ppList.length; i++) {
            if (priority < ppList[i].priority) {
              ppList.splice(i, 0, listElement);
              return;
            }
          }
          ppList.push(listElement);
        }
        _appendIn(ppList, listElement) {
          ppList.push(listElement);
        }
      } exports("Scheduler", Scheduler);
      Scheduler.ID = 'scheduler';
      legacyCC.Scheduler = Scheduler;

      const vmath = {};
      replaceProperty(vmath, 'vmath', [{
        name: 'vec2',
        newName: 'Vec2',
        target: math,
        targetName: 'math'
      }, {
        name: 'vec3',
        newName: 'Vec3',
        target: math,
        targetName: 'math'
      }, {
        name: 'vec4',
        newName: 'Vec4',
        target: math,
        targetName: 'math'
      }, {
        name: 'quat',
        newName: 'Quat',
        target: math,
        targetName: 'math'
      }, {
        name: 'mat3',
        newName: 'Mat3',
        target: math,
        targetName: 'math'
      }, {
        name: 'mat4',
        newName: 'Mat4',
        target: math,
        targetName: 'math'
      }, {
        name: 'color4',
        newName: 'Color',
        target: math,
        targetName: 'math'
      }, {
        name: 'rect',
        newName: 'Rect',
        target: math,
        targetName: 'math'
      }, {
        name: 'approx',
        newName: 'approx',
        target: math,
        targetName: 'math'
      }, {
        name: 'EPSILON',
        newName: 'EPSILON',
        target: math,
        targetName: 'math'
      }, {
        name: 'equals',
        newName: 'equals',
        target: math,
        targetName: 'math'
      }, {
        name: 'clamp',
        newName: 'clamp',
        target: math,
        targetName: 'math'
      }, {
        name: 'clamp01',
        newName: 'clamp01',
        target: math,
        targetName: 'math'
      }, {
        name: 'lerp',
        newName: 'lerp',
        target: math,
        targetName: 'math'
      }, {
        name: 'toRadian',
        newName: 'toRadian',
        target: math,
        targetName: 'math'
      }, {
        name: 'toDegree',
        newName: 'toDegree',
        target: math,
        targetName: 'math'
      }, {
        name: 'random',
        newName: 'random',
        target: math,
        targetName: 'math'
      }, {
        name: 'randomRange',
        newName: 'randomRange',
        target: math,
        targetName: 'math'
      }, {
        name: 'randomRangeInt',
        newName: 'randomRangeInt',
        target: math,
        targetName: 'math'
      }, {
        name: 'pseudoRandom',
        newName: 'pseudoRandom',
        target: math,
        targetName: 'math'
      }, {
        name: 'pseudoRandomRangeInt',
        newName: 'pseudoRandomRangeInt',
        target: math,
        targetName: 'math'
      }, {
        name: 'nextPow2',
        newName: 'nextPow2',
        target: math,
        targetName: 'math'
      }, {
        name: 'repeat',
        newName: 'repeat',
        target: math,
        targetName: 'math'
      }, {
        name: 'pingPong',
        newName: 'pingPong',
        target: math,
        targetName: 'math'
      }, {
        name: 'inverseLerp',
        newName: 'inverseLerp',
        target: math,
        targetName: 'math'
      }]);
      legacyCC.vmath = vmath;
      replaceProperty(Scheduler.prototype, 'Scheduler.prototype', [{
        name: 'enableForTarget',
        newName: 'enableForTarget',
        target: Scheduler,
        targetName: 'Scheduler'
      }]);
      replaceProperty(Scheduler, 'Scheduler', [{
        name: 'PRIORITY_SYSTEM',
        newName: 'System.Priority.SCHEDULER',
        customGetter() {
          return System.Priority.SCHEDULER;
        }
      }]);
      removeProperty(Scheduler, 'Scheduler', [{
        name: 'PRIORITY_NON_SYSTEM',
        suggest: 'Use enum` System.Priority` instead'
      }]);

      markAsWarning(js$1, 'js', [{
        name: 'js',
        suggest: `'js.js' is deprecated since v3.7.0, please access 'js' directly instead.`
      }]);

      const getUint8ForString = String.prototype.charCodeAt;
      function getUint8ForArray(idx) {
        return this[idx];
      }
      function murmurhash2_32_gc(input, seed) {
        let l = input.length;
        let h = seed ^ l;
        let i = 0;
        const getUint8 = typeof input === 'string' ? getUint8ForString : getUint8ForArray;
        while (l >= 4) {
          let 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) {
        const lpos = node._lpos;
        node.setPositionForJS(lpos.x, lpos.y, lpos.z);
        const lscale = node._lscale;
        node.setScaleForJS(lscale.x, lscale.y, lscale.z);
        const lrot = node._lrot;
        node.setRotationForJS(lrot.x, lrot.y, lrot.z, lrot.w);
        const euler = node._euler;
        node.setRotationFromEulerForJS(euler.x, euler.y, euler.z);
      }
      function updateChildrenForDeserialize(node) {
        if (!node) {
          return;
        }
        const children = node.children;
        if (!children) {
          return;
        }
        const len = children.length;
        if (!len) {
          return;
        }
        node._setChildren(children);
        for (let i = 0; i < len; ++i) {
          const 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,
        ExtraEventMethods: ExtraEventMethods,
        syncNodeValues: syncNodeValues,
        updateChildrenForDeserialize: updateChildrenForDeserialize
      });
      exports("jsbUtils", jsbUtils);

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

      class GarbageCollectionManager {
        constructor() {
          this._finalizationRegistry = null;
          this._gcObjects = new WeakMap();
        }
        registerGCObject(gcObject) {
          {
            return gcObject;
          }
        }
        init() {}
        finalizationRegistryCallback(token) {
          const gcObject = this._gcObjects.get(token);
          if (gcObject) {
            this._gcObjects.delete(token);
            gcObject.destroy();
          }
          this._finalizationRegistry.unregister(token);
        }
        destroy() {}
      }
      const garbageCollectionManager = exports("garbageCollectionManager", new GarbageCollectionManager());

      class GCObject {
        constructor() {
          return garbageCollectionManager.registerGCObject(this);
        }
        destroy() {}
      } exports("GCObject", GCObject);

      function deepFlatten(strList, array) {
        for (const item of array) {
          if (Array.isArray(item)) {
            deepFlatten(strList, item);
          } else {
            strList.push(item);
          }
        }
      }
      function flattenCodeArray(array) {
        const separator = '';
        const strList = [];
        deepFlatten(strList, array);
        return strList.join(separator);
      }

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

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

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

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

      function watchArrayElementsField(self, list, eleField, cachedFieldName, callback) {
        for (let i = 0, l = list.length; i < l; i++) {
          let ele = list[i];
          let originField = ele[eleField][cachedFieldName] || ele[eleField];
          ele[eleField] = new Proxy(originField, {
            get: (originTarget, key) => {
              if (key === cachedFieldName) {
                return originTarget;
              }
              return Reflect.get(originTarget, key);
            },
            set: (originTarget, prop, value) => {
              Reflect.set(originTarget, prop, value);
              callback(self, i, originTarget, prop, value);
              return true;
            }
          });
        }
      }
      class RasterizerState {
        constructor(isDiscard = false, polygonMode = 0, shadeModel = 0, cullMode = 2, isFrontFaceCCW = true, depthBiasEnabled = false, depthBias = 0, depthBiasClamp = 0.0, depthBiasSlop = 0.0, isDepthClip = true, isMultisample = false, lineWidth = 1.0) {
          this._nativeObj = void 0;
          this._isDiscard = false;
          this._polygonMode = 0;
          this._shadeModel = 0;
          this._cullMode = 2;
          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;
          this._nativeObj = new gfx.RasterizerState();
          this.assignProperties(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth);
        }
        get native() {
          return this._nativeObj;
        }
        get isDiscard() {
          return this._isDiscard;
        }
        set isDiscard(val) {
          this._isDiscard = val;
          this._nativeObj.isDiscard = val;
        }
        get polygonMode() {
          return this._polygonMode;
        }
        set polygonMode(val) {
          this._polygonMode = val;
          this._nativeObj.polygonMode = val;
        }
        get shadeModel() {
          return this._shadeModel;
        }
        set shadeModel(val) {
          this._shadeModel = val;
          this._nativeObj.shadeModel = val;
        }
        get cullMode() {
          return this._cullMode;
        }
        set cullMode(val) {
          this._cullMode = val;
          this._nativeObj.cullMode = val;
        }
        get isFrontFaceCCW() {
          return this._isFrontFaceCCW;
        }
        set isFrontFaceCCW(val) {
          this._isFrontFaceCCW = val;
          this._nativeObj.isFrontFaceCCW = val;
        }
        get depthBiasEnabled() {
          return this._depthBiasEnabled;
        }
        set depthBiasEnabled(val) {
          this._depthBiasEnabled = val;
          this._nativeObj.depthBiasEnabled = val;
        }
        get depthBias() {
          return this._depthBias;
        }
        set depthBias(val) {
          this._depthBias = val;
          this._nativeObj.depthBias = val;
        }
        get depthBiasClamp() {
          return this._depthBiasClamp;
        }
        set depthBiasClamp(val) {
          this._depthBiasClamp = val;
          this._nativeObj.depthBiasClamp = val;
        }
        get depthBiasSlop() {
          return this._depthBiasSlop;
        }
        set depthBiasSlop(val) {
          this._depthBiasSlop = val;
          this._nativeObj.depthBiasSlop = val;
        }
        get isDepthClip() {
          return this._isDepthClip;
        }
        set isDepthClip(val) {
          this._isDepthClip = val;
          this._nativeObj.isDepthClip = val;
        }
        get isMultisample() {
          return this._isMultisample;
        }
        set isMultisample(val) {
          this._isMultisample = val;
          this._nativeObj.isMultisample = val;
        }
        get lineWidth() {
          return this._lineWidth;
        }
        set lineWidth(val) {
          this._lineWidth = val;
          this._nativeObj.lineWidth = val;
        }
        reset() {
          this.assignProperties(false, 0, 0, 2, true, false, 0, 0.0, 0.0, true, false, 1.0);
        }
        assign(rs) {
          if (!rs) return;
          this.assignProperties(rs.isDiscard, rs.polygonMode, rs.shadeModel, rs.cullMode, rs.isFrontFaceCCW, rs.depthBiasEnabled, rs.depthBias, rs.depthBiasClamp, rs.depthBiasSlop, rs.isDepthClip, rs.isMultisample, rs.lineWidth);
        }
        destroy() {
          this._nativeObj = null;
        }
        assignProperties(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth) {
          if (isDiscard !== undefined) this.isDiscard = isDiscard;
          if (polygonMode !== undefined) this.polygonMode = polygonMode;
          if (shadeModel !== undefined) this.shadeModel = shadeModel;
          if (cullMode !== undefined) this.cullMode = cullMode;
          if (isFrontFaceCCW !== undefined) this.isFrontFaceCCW = isFrontFaceCCW;
          if (depthBiasEnabled !== undefined) this.depthBiasEnabled = depthBiasEnabled;
          if (depthBias !== undefined) this.depthBias = depthBias;
          if (depthBiasClamp !== undefined) this.depthBiasClamp = depthBiasClamp;
          if (depthBiasSlop !== undefined) this.depthBiasSlop = depthBiasSlop;
          if (isDepthClip !== undefined) this.isDepthClip = isDepthClip;
          if (isMultisample !== undefined) this.isMultisample = isMultisample;
          if (lineWidth !== undefined) this.lineWidth = lineWidth;
        }
      }
      class DepthStencilState {
        constructor(depthTest = true, depthWrite = true, depthFunc = 1, stencilTestFront = false, stencilFuncFront = 7, stencilReadMaskFront = 0xffff, stencilWriteMaskFront = 0xffff, stencilFailOpFront = 1, stencilZFailOpFront = 1, stencilPassOpFront = 1, stencilRefFront = 1, stencilTestBack = false, stencilFuncBack = 7, stencilReadMaskBack = 0xffff, stencilWriteMaskBack = 0xffff, stencilFailOpBack = 1, stencilZFailOpBack = 1, stencilPassOpBack = 1, stencilRefBack = 1) {
          this._nativeObj = void 0;
          this._depthTest = true;
          this._depthWrite = true;
          this._depthFunc = 1;
          this._stencilTestFront = false;
          this._stencilFuncFront = 7;
          this._stencilReadMaskFront = 0xffff;
          this._stencilWriteMaskFront = 0xffff;
          this._stencilFailOpFront = 1;
          this._stencilZFailOpFront = 1;
          this._stencilPassOpFront = 1;
          this._stencilRefFront = 1;
          this._stencilTestBack = false;
          this._stencilFuncBack = 7;
          this._stencilReadMaskBack = 0xffff;
          this._stencilWriteMaskBack = 0xffff;
          this._stencilFailOpBack = 1;
          this._stencilZFailOpBack = 1;
          this._stencilPassOpBack = 1;
          this._stencilRefBack = 1;
          this._nativeObj = new gfx.DepthStencilState();
          this.assignProperties(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack);
        }
        get native() {
          return this._nativeObj;
        }
        get depthTest() {
          return this._depthTest;
        }
        set depthTest(val) {
          this._depthTest = val;
          this._nativeObj.depthTest = val;
        }
        get depthWrite() {
          return this._depthWrite;
        }
        set depthWrite(val) {
          this._depthWrite = val;
          this._nativeObj.depthWrite = val;
        }
        get depthFunc() {
          return this._depthFunc;
        }
        set depthFunc(val) {
          this._depthFunc = val;
          this._nativeObj.depthFunc = val;
        }
        get stencilTestFront() {
          return this._stencilTestFront;
        }
        set stencilTestFront(val) {
          this._stencilTestFront = val;
          this._nativeObj.stencilTestFront = val;
        }
        get stencilFuncFront() {
          return this._stencilFuncFront;
        }
        set stencilFuncFront(val) {
          this._stencilFuncFront = val;
          this._nativeObj.stencilFuncFront = val;
        }
        get stencilReadMaskFront() {
          return this._stencilReadMaskFront;
        }
        set stencilReadMaskFront(val) {
          this._stencilReadMaskFront = val;
          this._nativeObj.stencilReadMaskFront = val;
        }
        get stencilWriteMaskFront() {
          return this._stencilWriteMaskFront;
        }
        set stencilWriteMaskFront(val) {
          this._stencilWriteMaskFront = val;
          this._nativeObj.stencilWriteMaskFront = val;
        }
        get stencilFailOpFront() {
          return this._stencilFailOpFront;
        }
        set stencilFailOpFront(val) {
          this._stencilFailOpFront = val;
          this._nativeObj.stencilFailOpFront = val;
        }
        get stencilZFailOpFront() {
          return this._stencilZFailOpFront;
        }
        set stencilZFailOpFront(val) {
          this._stencilZFailOpFront = val;
          this._nativeObj.stencilZFailOpFront = val;
        }
        get stencilPassOpFront() {
          return this._stencilPassOpFront;
        }
        set stencilPassOpFront(val) {
          this._stencilPassOpFront = val;
          this._nativeObj.stencilPassOpFront = val;
        }
        get stencilRefFront() {
          return this._stencilRefFront;
        }
        set stencilRefFront(val) {
          this._stencilRefFront = val;
          this._nativeObj.stencilRefFront = val;
        }
        get stencilTestBack() {
          return this._stencilTestBack;
        }
        set stencilTestBack(val) {
          this._stencilTestBack = val;
          this._nativeObj.stencilTestBack = val;
        }
        get stencilFuncBack() {
          return this._stencilFuncBack;
        }
        set stencilFuncBack(val) {
          this._stencilFuncBack = val;
          this._nativeObj.stencilFuncBack = val;
        }
        get stencilReadMaskBack() {
          return this._stencilReadMaskBack;
        }
        set stencilReadMaskBack(val) {
          this._stencilReadMaskBack = val;
          this._nativeObj.stencilReadMaskBack = val;
        }
        get stencilWriteMaskBack() {
          return this._stencilWriteMaskBack;
        }
        set stencilWriteMaskBack(val) {
          this._stencilWriteMaskBack = val;
          this._nativeObj.stencilWriteMaskBack = val;
        }
        get stencilFailOpBack() {
          return this._stencilFailOpBack;
        }
        set stencilFailOpBack(val) {
          this._stencilFailOpBack = val;
          this._nativeObj.stencilFailOpBack = val;
        }
        get stencilZFailOpBack() {
          return this._stencilZFailOpBack;
        }
        set stencilZFailOpBack(val) {
          this._stencilZFailOpBack = val;
          this._nativeObj.stencilZFailOpBack = val;
        }
        get stencilPassOpBack() {
          return this._stencilPassOpBack;
        }
        set stencilPassOpBack(val) {
          this._stencilPassOpBack = val;
          this._nativeObj.stencilPassOpBack = val;
        }
        get stencilRefBack() {
          return this._stencilRefBack;
        }
        set stencilRefBack(val) {
          this._stencilRefBack = val;
          this._nativeObj.stencilRefBack = val;
        }
        reset() {
          this.assignProperties(true, true, 1, false, 7, 0xffff, 0xffff, 1, 1, 1, 1, false, 7, 0xffff, 0xffff, 1, 1, 1, 1);
        }
        assign(dss) {
          if (!dss) return;
          this.assignProperties(dss.depthTest, dss.depthWrite, dss.depthFunc, dss.stencilTestFront, dss.stencilFuncFront, dss.stencilReadMaskFront, dss.stencilWriteMaskFront, dss.stencilFailOpFront, dss.stencilZFailOpFront, dss.stencilPassOpFront, dss.stencilRefFront, dss.stencilTestBack, dss.stencilFuncBack, dss.stencilReadMaskBack, dss.stencilWriteMaskBack, dss.stencilFailOpBack, dss.stencilZFailOpBack, dss.stencilPassOpBack, dss.stencilRefBack);
        }
        destroy() {
          this._nativeObj = null;
        }
        assignProperties(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack) {
          if (depthTest !== undefined) this.depthTest = depthTest;
          if (depthWrite !== undefined) this.depthWrite = depthWrite;
          if (depthFunc !== undefined) this.depthFunc = depthFunc;
          if (stencilTestFront !== undefined) this.stencilTestFront = stencilTestFront;
          if (stencilFuncFront !== undefined) this.stencilFuncFront = stencilFuncFront;
          if (stencilReadMaskFront !== undefined) this.stencilReadMaskFront = stencilReadMaskFront;
          if (stencilWriteMaskFront !== undefined) this.stencilWriteMaskFront = stencilWriteMaskFront;
          if (stencilFailOpFront !== undefined) this.stencilFailOpFront = stencilFailOpFront;
          if (stencilZFailOpFront !== undefined) this.stencilZFailOpFront = stencilZFailOpFront;
          if (stencilPassOpFront !== undefined) this.stencilPassOpFront = stencilPassOpFront;
          if (stencilRefFront !== undefined) this.stencilRefFront = stencilRefFront;
          if (stencilTestBack !== undefined) this.stencilTestBack = stencilTestBack;
          if (stencilFuncBack !== undefined) this.stencilFuncBack = stencilFuncBack;
          if (stencilReadMaskBack !== undefined) this.stencilReadMaskBack = stencilReadMaskBack;
          if (stencilWriteMaskBack !== undefined) this.stencilWriteMaskBack = stencilWriteMaskBack;
          if (stencilFailOpBack !== undefined) this.stencilFailOpBack = stencilFailOpBack;
          if (stencilZFailOpBack !== undefined) this.stencilZFailOpBack = stencilZFailOpBack;
          if (stencilPassOpBack !== undefined) this.stencilPassOpBack = stencilPassOpBack;
          if (stencilRefBack !== undefined) this.stencilRefBack = stencilRefBack;
        }
      }
      class BlendTarget {
        get native() {
          return this._nativeObj;
        }
        constructor(blend = false, blendSrc = 1, blendDst = 0, blendEq = 0, blendSrcAlpha = 1, blendDstAlpha = 0, blendAlphaEq = 0, blendColorMask = 15) {
          this._nativeObj = void 0;
          this._blend = false;
          this._blendSrc = 1;
          this._blendDst = 0;
          this._blendEq = 0;
          this._blendSrcAlpha = 1;
          this._blendDstAlpha = 0;
          this._blendAlphaEq = 0;
          this._blendColorMask = 15;
          this._nativeObj = new gfx.BlendTarget();
          this.assignProperties(blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask);
        }
        get blend() {
          return this._blend;
        }
        set blend(val) {
          this._blend = val;
          this._nativeObj.blend = val;
        }
        get blendSrc() {
          return this._blendSrc;
        }
        set blendSrc(val) {
          this._blendSrc = val;
          this._nativeObj.blendSrc = val;
        }
        get blendDst() {
          return this._blendDst;
        }
        set blendDst(val) {
          this._blendDst = val;
          this._nativeObj.blendDst = val;
        }
        get blendEq() {
          return this._blendEq;
        }
        set blendEq(val) {
          this._blendEq = val;
          this._nativeObj.blendEq = val;
        }
        get blendSrcAlpha() {
          return this._blendSrcAlpha;
        }
        set blendSrcAlpha(val) {
          this._blendSrcAlpha = val;
          this._nativeObj.blendSrcAlpha = val;
        }
        get blendDstAlpha() {
          return this._blendDstAlpha;
        }
        set blendDstAlpha(val) {
          this._blendDstAlpha = val;
          this._nativeObj.blendDstAlpha = val;
        }
        get blendAlphaEq() {
          return this._blendAlphaEq;
        }
        set blendAlphaEq(val) {
          this._blendAlphaEq = val;
          this._nativeObj.blendAlphaEq = val;
        }
        get blendColorMask() {
          return this._blendColorMask;
        }
        set blendColorMask(val) {
          this._blendColorMask = val;
          this._nativeObj.blendColorMask = val;
        }
        reset() {
          this.assignProperties(false, 1, 0, 0, 1, 0, 0, 15);
        }
        destroy() {
          this._nativeObj = null;
        }
        assign(target) {
          if (!target) return;
          this.assignProperties(target.blend, target.blendSrc, target.blendDst, target.blendEq, target.blendSrcAlpha, target.blendDstAlpha, target.blendAlphaEq, target.blendColorMask);
        }
        assignProperties(blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask) {
          if (blend !== undefined) this.blend = blend;
          if (blendSrc !== undefined) this.blendSrc = blendSrc;
          if (blendDst !== undefined) this.blendDst = blendDst;
          if (blendEq !== undefined) this.blendEq = blendEq;
          if (blendSrcAlpha !== undefined) this.blendSrcAlpha = blendSrcAlpha;
          if (blendDstAlpha !== undefined) this.blendDstAlpha = blendDstAlpha;
          if (blendAlphaEq !== undefined) this.blendAlphaEq = blendAlphaEq;
          if (blendColorMask !== undefined) this.blendColorMask = blendColorMask;
        }
      }
      class BlendState {
        _setTargets(targets) {
          this.targets = targets;
          const CACHED_FIELD_NAME = `$__nativeObj`;
          this._syncTargetsToNativeObj(CACHED_FIELD_NAME);
          watchArrayElementsField(this, this.targets, "_nativeObj", CACHED_FIELD_NAME, (self, _idx, _originTarget, _prop, _value) => {
            self._syncTargetsToNativeObj(CACHED_FIELD_NAME);
          });
        }
        _syncTargetsToNativeObj(cachedFieldName) {
          const nativeTars = this.targets.map(target => {
            return target.native[cachedFieldName] || target.native;
          });
          this._nativeObj.targets = nativeTars;
        }
        get native() {
          return this._nativeObj;
        }
        constructor(isA2C = false, isIndepend = false, blendColor = new Color(), targets = [new BlendTarget()]) {
          this.targets = void 0;
          this._blendColor = void 0;
          this._nativeObj = void 0;
          this._isA2C = false;
          this._isIndepend = false;
          this._nativeObj = new gfx.BlendState();
          this._setTargets(targets);
          this.blendColor = blendColor;
          this.isA2C = isA2C;
          this.isIndepend = isIndepend;
        }
        get isA2C() {
          return this._isA2C;
        }
        set isA2C(val) {
          this._isA2C = val;
          this._nativeObj.isA2C = val;
        }
        get isIndepend() {
          return this._isIndepend;
        }
        set isIndepend(val) {
          this._isIndepend = val;
          this._nativeObj.isIndepend = val;
        }
        get blendColor() {
          return this._blendColor;
        }
        set blendColor(color) {
          this._blendColor = color;
          this._nativeObj.blendColor = color;
        }
        setTarget(index, target) {
          let tg = this.targets[index];
          if (!tg) {
            tg = this.targets[index] = new BlendTarget();
          }
          tg.assign(target);
          this._setTargets(this.targets);
        }
        reset() {
          this.isA2C = false;
          this.isIndepend = false;
          this.blendColor = new Color(0, 0, 0, 0);
          const targets = this.targets;
          for (let i = 1, len = targets.length; i < len; ++i) {
            targets[i].destroy();
          }
          targets.length = 1;
          targets[0].reset();
          this._setTargets(targets);
        }
        destroy() {
          for (let i = 0, len = this.targets.length; i < len; ++i) {
            this.targets[i].destroy();
          }
          this.targets = null;
          this._nativeObj = null;
        }
      }

      gfx.PipelineState;
      const PipelineStateInfo = gfx.PipelineStateInfo;

      const LegacyRenderMode = {
        "AUTO": 0,
        "CANVAS": 1,
        "WEBGL": 2,
        "HEADLESS": 3,
        "WEBGPU": 4
      };
      const RenderType = {
        "UNKNOWN": -1,
        "CANVAS": 0,
        "WEBGL": 1,
        "WEBGPU": 2,
        "OPENGL": 3,
        "HEADLESS": 4
      };
      class DeviceManager {
        constructor() {
          this.initialized = false;
          this._gfxDevice = void 0;
          this._canvas = null;
          this._swapchain = void 0;
          this._renderType = -1;
          this._deviceInitialized = false;
        }
        get gfxDevice() {
          return this._gfxDevice;
        }
        get swapchain() {
          return this._swapchain;
        }
        _tryInitializeWebGPUDevice(DeviceConstructor, info) {
          if (this._deviceInitialized) {
            return Promise.resolve(true);
          }
          if (DeviceConstructor) {
            this._gfxDevice = new DeviceConstructor();
            return new Promise((resolve, reject) => {
              this._gfxDevice.initialize(info).then(val => {
                this._deviceInitialized = val;
                resolve(val);
              }).catch(err => {
                reject(err);
              });
            });
          }
          return Promise.resolve(false);
        }
        _tryInitializeDeviceSync(DeviceConstructor, info) {
          if (this._deviceInitialized) {
            return true;
          }
          if (DeviceConstructor) {
            this._gfxDevice = new DeviceConstructor();
            this._deviceInitialized = this._gfxDevice.initialize(info);
          }
          return this._deviceInitialized;
        }
        init(canvas, bindingMappingInfo) {
          if (this.initialized) {
            return true;
          }
          const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
          this._canvas = canvas;
          if (this._canvas) {
            this._canvas.oncontextmenu = () => false;
          }
          this._renderType = this._determineRenderType(renderMode);
          this._deviceInitialized = false;
          const deviceInfo = new DeviceInfo(bindingMappingInfo);
          if (this._renderType === 1 || this._renderType === 2) {
            if (globalThis.gfx) {
              this._gfxDevice = gfx.DeviceManager.create(deviceInfo);
            } else {
              let useWebGL2 = !!globalThis.WebGL2RenderingContext;
              globalThis.navigator.userAgent.toLowerCase();
              if (sys.browserType === BrowserType.UC) {
                useWebGL2 = false;
              }
              if (this._renderType === 2 && cclegacy.WebGPUDevice) {
                return new Promise((resolve, reject) => {
                  this._tryInitializeWebGPUDevice(cclegacy.WebGPUDevice, deviceInfo).then(val => {
                    this._initSwapchain();
                    resolve(val);
                  }).catch(err => {
                    reject(err);
                  });
                });
              }
              if (useWebGL2 && cclegacy.WebGL2Device) {
                this._tryInitializeDeviceSync(cclegacy.WebGL2Device, deviceInfo);
              }
              if (cclegacy.WebGLDevice) {
                this._tryInitializeDeviceSync(cclegacy.WebGLDevice, deviceInfo);
              }
              if (cclegacy.EmptyDevice) {
                this._tryInitializeDeviceSync(cclegacy.EmptyDevice, deviceInfo);
              }
              this._initSwapchain();
            }
          } else if (this._renderType === 4 && cclegacy.EmptyDevice) {
            this._tryInitializeDeviceSync(cclegacy.EmptyDevice, deviceInfo);
            this._initSwapchain();
          }
          if (!this._gfxDevice) {
            errorID(16337);
            this._renderType = -1;
            return false;
          }
          return true;
        }
        _initSwapchain() {
          const swapchainInfo = new SwapchainInfo(1, this._canvas);
          const windowSize = screen.windowSize;
          swapchainInfo.width = windowSize.width;
          swapchainInfo.height = windowSize.height;
          this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo);
        }
        _supportWebGPU() {
          return 'gpu' in globalThis.navigator;
        }
        _determineRenderType(renderMode) {
          if (typeof renderMode !== 'number' || renderMode > 4 || renderMode < 0) {
            renderMode = 0;
          }
          let renderType = 0;
          let supportRender = false;
          if (renderMode === 1) {
            renderType = 0;
            supportRender = true;
          } else if (renderMode === 0 || renderMode === 4) {
            renderType = this._supportWebGPU() && !EDITOR ? 2 : 1;
            supportRender = true;
          } else if (renderMode === 2) {
            renderType = 1;
            supportRender = true;
          } else if (renderMode === 3) {
            renderType = 4;
            supportRender = true;
          }
          if (!supportRender) {
            throw new Error(getError(3820, renderMode));
          }
          return renderType;
        }
      }
      const deviceManager = new DeviceManager();

      const polyfills = {
        GFXDevice: true,
        GFXBuffer: true,
        GFXTexture: true,
        GFXSampler: true,
        GFXShader: true,
        GFXInputAssembler: true,
        GFXRenderPass: true,
        GFXFramebuffer: true,
        GFXPipelineState: true,
        GFXCommandBuffer: true,
        GFXQueue: true,
        GFXObjectType: true,
        GFXObject: false,
        GFXAttributeName: true,
        GFXType: true,
        GFXFormat: true,
        GFXBufferUsageBit: true,
        GFXMemoryUsageBit: true,
        GFXBufferFlagBit: true,
        GFXBufferAccessBit: 'MemoryAccessBit',
        GFXPrimitiveMode: true,
        GFXPolygonMode: true,
        GFXShadeModel: true,
        GFXCullMode: true,
        GFXComparisonFunc: true,
        GFXStencilOp: true,
        GFXBlendOp: true,
        GFXBlendFactor: true,
        GFXColorMask: true,
        GFXFilter: true,
        GFXAddress: true,
        GFXTextureType: true,
        GFXTextureUsageBit: true,
        GFXSampleCount: true,
        GFXTextureFlagBit: true,
        GFXShaderStageFlagBit: true,
        GFXDescriptorType: true,
        GFXCommandBufferType: true,
        GFXLoadOp: true,
        GFXStoreOp: true,
        GFXPipelineBindPoint: true,
        GFXDynamicStateFlagBit: true,
        GFXStencilFace: true,
        GFXQueueType: true,
        GFXRect: true,
        GFXViewport: true,
        GFXColor: true,
        GFXClearFlag: true,
        GFXOffset: true,
        GFXExtent: true,
        GFXTextureSubres: 'TextureSubresLayers',
        GFXTextureCopy: true,
        GFXBufferTextureCopy: true,
        GFXFormatType: true,
        GFXFormatInfo: true,
        GFXMemoryStatus: true,
        GFXFormatInfos: true,
        GFXFormatSize: true,
        GFXFormatSurfaceSize: true,
        GFXGetTypeSize: true,
        getTypedArrayConstructor: false
      };
      for (const name in polyfills) {
        let newName = polyfills[name];
        if (newName === true) {
          newName = name.slice(3);
        } else if (newName === false) {
          newName = name;
        }
        replaceProperty(cclegacy, 'cc', [{
          name,
          newName,
          target: cclegacy.gfx,
          targetName: 'cc.gfx'
        }]);
      }
      removeProperty(cclegacy, 'cc', [{
        name: 'GFX_MAX_VERTEX_ATTRIBUTES'
      }, {
        name: 'GFX_MAX_TEXTURE_UNITS'
      }, {
        name: 'GFX_MAX_ATTACHMENTS'
      }, {
        name: 'GFX_MAX_BUFFER_BINDINGS'
      }, {
        name: 'GFXTextureLayout'
      }]);

      const DescriptorSet = gfx.DescriptorSet;
      const Buffer = gfx.Buffer;
      const CommandBuffer = gfx.CommandBuffer;
      const Device = gfx.Device;
      const Swapchain = gfx.Swapchain;
      const Framebuffer = gfx.Framebuffer;
      const InputAssembler = gfx.InputAssembler;
      const DescriptorSetLayout = gfx.DescriptorSetLayout;
      const PipelineLayout = gfx.PipelineLayout;
      const PipelineState = gfx.PipelineState;
      const Queue = gfx.Queue;
      const RenderPass = gfx.RenderPass;
      const Shader = gfx.Shader;
      const Texture = gfx.Texture;
      const Sampler = gfx.Sampler;
      const GeneralBarrier = gfx.GeneralBarrier;
      const TextureBarrier = gfx.TextureBarrier;
      const polyfillCC = Object.assign({}, defines);
      polyfillCC.GFXObject = gfx.GFXObject;
      polyfillCC.Device = gfx.Device;
      polyfillCC.Swapchain = gfx.Swapchain;
      polyfillCC.Buffer = gfx.Buffer;
      polyfillCC.Texture = gfx.Texture;
      polyfillCC.Sampler = gfx.Sampler;
      polyfillCC.Shader = gfx.Shader;
      polyfillCC.InputAssembler = gfx.InputAssembler;
      polyfillCC.RenderPass = gfx.RenderPass;
      polyfillCC.Framebuffer = gfx.Framebuffer;
      polyfillCC.DescriptorSet = gfx.DescriptorSet;
      polyfillCC.DescriptorSetLayout = gfx.DescriptorSetLayout;
      polyfillCC.PipelineLayout = gfx.PipelineLayout;
      polyfillCC.PipelineState = gfx.PipelineState;
      polyfillCC.CommandBuffer = gfx.CommandBuffer;
      polyfillCC.Queue = gfx.Queue;
      polyfillCC.GeneralBarrier = gfx.GeneralBarrier;
      polyfillCC.TextureBarrier = gfx.TextureBarrier;
      cclegacy.gfx = polyfillCC;
      polyfillCC.BlendTarget = BlendTarget;
      polyfillCC.BlendState = BlendState;
      polyfillCC.RasterizerState = RasterizerState;
      polyfillCC.DepthStencilState = DepthStencilState;
      polyfillCC.PipelineStateInfo = PipelineStateInfo;

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

      const _col$1 = new Vec4();
      function fillMeshVertices3D(node, renderer, renderData, color) {
        const chunk = renderData.chunk;
        const dataList = renderData.data;
        const vData = chunk.vb;
        const vertexCount = renderData.vertexCount;
        const m = node.worldMatrix;
        const m00 = m.m00;
        const m01 = m.m01;
        const m02 = m.m02;
        const m03 = m.m03;
        const m04 = m.m04;
        const m05 = m.m05;
        const m06 = m.m06;
        const m07 = m.m07;
        const m12 = m.m12;
        const m13 = m.m13;
        const m14 = m.m14;
        const m15 = m.m15;
        _col$1.set(color.r / 255, color.g / 255, color.b / 255, color.a / 255);
        let vertexOffset = 0;
        for (let i = 0; i < vertexCount; ++i) {
          const vert = dataList[i];
          const x = vert.x;
          const y = vert.y;
          let rhw = m03 * x + m07 * y + m15;
          rhw = rhw ? 1 / rhw : 1;
          vData[vertexOffset + 0] = (m00 * x + m04 * y + m12) * rhw;
          vData[vertexOffset + 1] = (m01 * x + m05 * y + m13) * rhw;
          vData[vertexOffset + 2] = (m02 * x + m06 * y + m14) * rhw;
          Vec4.toArray(vData, _col$1, vertexOffset + 5);
          vertexOffset += 9;
        }
        chunk.bufferId;
        const vid = chunk.vertexOffset;
        const meshBuffer = chunk.meshBuffer;
        const ib = chunk.meshBuffer.iData;
        let indexOffset = meshBuffer.indexOffset;
        for (let i = 0, count = vertexCount / 4; i < count; i++) {
          const 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) {
        const vfmt = renderData.vertexFormat;
        const vb = renderData.chunk.vb;
        let attr;
        let format;
        let stride;
        let offset = 0;
        for (let 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) {
              const alpha = ~~clamp$1(Math.round(opacity * 255), 0, 255);
              for (let color = offset; color < vb.length; color += stride) {
                vb[color] = (vb[color] & 0xffffff00 | alpha) >>> 0;
              }
            } else if (format.size / format.count === 4) {
              for (let alpha = offset + 3; alpha < vb.length; alpha += stride) {
                vb[alpha] = opacity;
              }
            }
          }
          offset += format.size >> 2;
        }
      }

      const minigame = {};

      class Cache {
        get map() {
          return this._map;
        }
        constructor(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;
          }
        }
        add(key, val) {
          if (!(key in this._map)) {
            this._count++;
          }
          return this._map[key] = val;
        }
        get(key) {
          return this._map[key];
        }
        has(key) {
          return key in this._map;
        }
        remove(key) {
          const out = this._map[key];
          if (key in this._map) {
            delete this._map[key];
            this._count--;
          }
          return out;
        }
        clear() {
          if (this._count !== 0) {
            this._map = createMap(true);
            this._count = 0;
          }
        }
        forEach(func) {
          for (const key in this._map) {
            func(this._map[key], key);
          }
        }
        find(predicate) {
          for (const key in this._map) {
            if (predicate(this._map[key], key)) {
              return this._map[key];
            }
          }
          return null;
        }
        get count() {
          return this._count;
        }
        destroy() {
          this._map = null;
        }
      }

      class Pipeline {
        constructor(name, funcs) {
          this.id = Pipeline._pipelineId++;
          this.name = '';
          this.pipes = [];
          this.name = name;
          for (let i = 0, l = funcs.length; i < l; i++) {
            this.pipes.push(funcs[i]);
          }
        }
        insert(func, index) {
          if (index > this.pipes.length) {
            warnID(4921);
            return this;
          }
          this.pipes.splice(index, 0, func);
          return this;
        }
        append(func) {
          this.pipes.push(func);
          return this;
        }
        remove(index) {
          this.pipes.splice(index, 1);
          return this;
        }
        sync(task) {
          const pipes = this.pipes;
          if (pipes.length === 0) {
            return null;
          }
          task.isFinished = false;
          for (let i = 0, l = pipes.length; i < l;) {
            const pipe = pipes[i];
            const 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;
        }
        async(task) {
          const pipes = this.pipes;
          if (pipes.length === 0) {
            return;
          }
          task.isFinished = false;
          this._flow(0, task);
        }
        _flow(index, task) {
          const pipe = this.pipes[index];
          pipe(task, 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);
              }
            }
          });
        }
      }
      Pipeline._pipelineId = 0;

      const assets = new Cache();
      const files = new Cache();
      const parsed = new Cache();
      const bundles = new Cache();
      const pipeline = new Pipeline('normal load', []);
      const fetchPipeline = new Pipeline('fetch', []);
      const transformPipeline = new Pipeline('transform url', []);
      const references = null;
      const assetsOverrideMap = new Map();
      const 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
        }
      };
      const BuiltinBundleName = {
        "INTERNAL": "internal",
        "RESOURCES": "resources",
        "MAIN": "main",
        "START_SCENE": "start-scene"
      };

      class Task {
        static create(options) {
          let out;
          if (Task._deadPool.length !== 0) {
            out = Task._deadPool.pop();
            out.set(options);
          } else {
            out = new Task(options);
          }
          return out;
        }
        get isFinish() {
          return this.isFinished;
        }
        set isFinish(val) {
          this.isFinished = val;
        }
        constructor(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);
        }
        set(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);
        }
        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:
              {
                const str = `on${event[0].toUpperCase()}${event.substr(1)}`;
                if (typeof this[str] === 'function') {
                  this[str](param1, param2, param3, param4);
                }
                break;
              }
          }
        }
        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);
        }
      }
      Task.MAX_DEAD_NUM = 500;
      Task._taskId = 0;
      Task._deadPool = [];

      const separator = '@';
      const HexChars = '0123456789abcdef'.split('');
      const _t = ['', '', '', ''];
      const UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);
      const Indices = UuidTemplate.map((x, i) => x === '-' ? NaN : i).filter(Number.isFinite);
      function decodeUuid(base64) {
        const strs = base64.split(separator);
        const uuid = strs[0];
        if (uuid.length !== 22) {
          return base64;
        }
        UuidTemplate[0] = base64[0];
        UuidTemplate[1] = base64[1];
        for (let i = 2, j = 2; i < 22; i += 2) {
          const lhs = BASE64_VALUES$1[base64.charCodeAt(i)];
          const rhs = BASE64_VALUES$1[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(''));
      }

      const _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/;
      function getUuidFromURL(url) {
        const 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;
        }
        const bundle = bundles.find(b => !!b.getAssetInfo(uuid));
        if (bundle) {
          options.bundle = bundle.name;
        }
        return transform(uuid, options);
      }
      function isScene(asset) {
        return !!asset && (asset instanceof cclegacy.SceneAsset || asset instanceof cclegacy.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) {
        const subTask = Task.create({
          input,
          options
        });
        const urls = [];
        try {
          const result = transformPipeline.sync(subTask);
          for (const requestItem of result) {
            const url = requestItem.url;
            requestItem.recycle();
            urls.push(url);
          }
        } catch (e) {
          for (const item of subTask.output) {
            item.recycle();
          }
          error(e.message, e.stack);
        }
        subTask.recycle();
        return urls.length > 1 ? urls : urls[0];
      }

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

      const defaultExec = (cb, decorator, attr) => {
        cb();
      };
      function patch_BloomStage(ctx, apply = defaultExec) {
        const {
          BloomStage,
          Material
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(BloomStage.prototype, '_bloomMaterial', () => {
            return null;
          });
        }, 'displayOrder', '_bloomMaterial');
        apply(() => {
          serializable$l(BloomStage.prototype, '_bloomMaterial', () => {
            return null;
          });
        }, 'serializable', '_bloomMaterial');
        apply(() => {
          type$a(Material)(BloomStage.prototype, '_bloomMaterial', () => {
            return null;
          });
        }, 'type', '_bloomMaterial');
        apply(() => {
          ccclass$H('BloomStage')(BloomStage);
        }, 'ccclass', null);
      }
      function patch_cc_AmbientInfo(ctx, apply = defaultExec) {
        const {
          AmbientInfo,
          legacyCC,
          CCFloat,
          Vec4,
          Ambient
        } = {
          ...ctx
        };
        const skyLightingColorDescriptor = Object.getOwnPropertyDescriptor(AmbientInfo.prototype, 'skyLightingColor');
        const skyIllumDescriptor = Object.getOwnPropertyDescriptor(AmbientInfo.prototype, 'skyIllum');
        const groundLightingColorDescriptor = Object.getOwnPropertyDescriptor(AmbientInfo.prototype, 'groundLightingColor');
        apply(() => {
          tooltip$1()(AmbientInfo.prototype, 'skyLightingColor', skyLightingColorDescriptor);
        }, 'tooltip', 'skyLightingColor');
        apply(() => {
          editable$5(AmbientInfo.prototype);
        }, 'editable', 'skyLightingColor');
        apply(() => {
          visible$3()(AmbientInfo.prototype, 'skyLightingColor', skyLightingColorDescriptor);
        }, 'visible', 'skyLightingColor');
        apply(() => {
          range()(AmbientInfo.prototype, 'skyIllum', skyIllumDescriptor);
        }, 'range', 'skyIllum');
        apply(() => {
          tooltip$1()(AmbientInfo.prototype, 'skyIllum', skyIllumDescriptor);
        }, 'tooltip', 'skyIllum');
        apply(() => {
          type$a(CCFloat)(AmbientInfo.prototype, 'skyIllum', skyIllumDescriptor);
        }, 'type', 'skyIllum');
        apply(() => {
          editable$5(AmbientInfo.prototype);
        }, 'editable', 'skyIllum');
        apply(() => {
          tooltip$1()(AmbientInfo.prototype, 'groundLightingColor', groundLightingColorDescriptor);
        }, 'tooltip', 'groundLightingColor');
        apply(() => {
          editable$5(AmbientInfo.prototype);
        }, 'editable', 'groundLightingColor');
        apply(() => {
          visible$3()(AmbientInfo.prototype, 'groundLightingColor', groundLightingColorDescriptor);
        }, 'visible', 'groundLightingColor');
        apply(() => {
          formerlySerializedAs$2('_skyColor')(AmbientInfo.prototype, '_skyColorHDR', () => {
            return new Vec4(0.2, 0.5, 0.8, 1.0);
          });
        }, 'formerlySerializedAs', '_skyColorHDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_skyColorHDR', () => {
            return new Vec4(0.2, 0.5, 0.8, 1.0);
          });
        }, 'serializable', '_skyColorHDR');
        apply(() => {
          formerlySerializedAs$2('_skyIllum')(AmbientInfo.prototype, '_skyIllumHDR', () => {
            return Ambient.SKY_ILLUM;
          });
        }, 'formerlySerializedAs', '_skyIllumHDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_skyIllumHDR', () => {
            return Ambient.SKY_ILLUM;
          });
        }, 'serializable', '_skyIllumHDR');
        apply(() => {
          formerlySerializedAs$2('_groundAlbedo')(AmbientInfo.prototype, '_groundAlbedoHDR', () => {
            return new Vec4(0.2, 0.2, 0.2, 1.0);
          });
        }, 'formerlySerializedAs', '_groundAlbedoHDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_groundAlbedoHDR', () => {
            return new Vec4(0.2, 0.2, 0.2, 1.0);
          });
        }, 'serializable', '_groundAlbedoHDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_skyColorLDR', () => {
            return new Vec4(0.2, 0.5, 0.8, 1.0);
          });
        }, 'serializable', '_skyColorLDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_skyIllumLDR', () => {
            return Ambient.SKY_ILLUM;
          });
        }, 'serializable', '_skyIllumLDR');
        apply(() => {
          serializable$l(AmbientInfo.prototype, '_groundAlbedoLDR', () => {
            return new Vec4(0.2, 0.2, 0.2, 1.0);
          });
        }, 'serializable', '_groundAlbedoLDR');
        apply(() => {
          ccclass$H('cc.AmbientInfo')(AmbientInfo);
        }, 'ccclass', null);
      }
      function patch_cc_Asset(ctx, apply = defaultExec) {
        const {
          Asset
        } = {
          ...ctx
        };
        const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(Asset.prototype, '_nativeAsset');
        apply(() => {
          serializable$l(Asset.prototype, '_native', () => {
            return '';
          });
        }, 'serializable', '_native');
        apply(() => {
          property(Asset.prototype, '_nativeAsset', _nativeAssetDescriptor);
        }, 'property', '_nativeAsset');
        apply(() => {
          ccclass$H('cc.Asset')(Asset);
        }, 'ccclass', null);
      }
      function patch_cc_BufferAsset(ctx, apply = defaultExec) {
        const {
          BufferAsset
        } = {
          ...ctx
        };
        const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(BufferAsset.prototype, '_nativeAsset');
        apply(() => {
          override$1(BufferAsset.prototype, '_nativeAsset', _nativeAssetDescriptor);
        }, 'override', '_nativeAsset');
        apply(() => {
          ccclass$H('cc.BufferAsset')(BufferAsset);
        }, 'ccclass', null);
      }
      function patch_cc_CircumSphere(ctx, apply = defaultExec) {
        const {
          CircumSphere,
          Vec3
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(CircumSphere.prototype, 'center', () => {
            return new Vec3(0, 0, 0);
          });
        }, 'serializable', 'center');
        apply(() => {
          serializable$l(CircumSphere.prototype, 'radiusSquared', () => {
            return 0.0;
          });
        }, 'serializable', 'radiusSquared');
        apply(() => {
          ccclass$H('cc.CircumSphere')(CircumSphere);
        }, 'ccclass', null);
      }
      function patch_cc_EffectAsset(ctx, apply = defaultExec) {
        const {
          EffectAsset
        } = {
          ...ctx
        };
        apply(() => {
          editable$5(EffectAsset.prototype);
        }, 'editable', 'techniques');
        apply(() => {
          serializable$l(EffectAsset.prototype, 'techniques', () => {
            return [];
          });
        }, 'serializable', 'techniques');
        apply(() => {
          editable$5(EffectAsset.prototype);
        }, 'editable', 'shaders');
        apply(() => {
          serializable$l(EffectAsset.prototype, 'shaders', () => {
            return [];
          });
        }, 'serializable', 'shaders');
        apply(() => {
          editable$5(EffectAsset.prototype);
        }, 'editable', 'combinations');
        apply(() => {
          serializable$l(EffectAsset.prototype, 'combinations', () => {
            return [];
          });
        }, 'serializable', 'combinations');
        apply(() => {
          editorOnly(EffectAsset.prototype, 'hideInEditor', () => {
            return false;
          });
        }, 'editorOnly', 'hideInEditor');
        apply(() => {
          serializable$l(EffectAsset.prototype, 'hideInEditor', () => {
            return false;
          });
        }, 'serializable', 'hideInEditor');
        apply(() => {
          ccclass$H('cc.EffectAsset')(EffectAsset);
        }, 'ccclass', null);
      }
      function patch_cc_FogInfo(ctx, apply = defaultExec) {
        const {
          FogInfo,
          FogType,
          CCFloat,
          Color
        } = {
          ...ctx
        };
        const enabledDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'enabled');
        const accurateDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'accurate');
        const fogColorDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogColor');
        const typeDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'type');
        const fogDensityDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogDensity');
        const fogStartDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogStart');
        const fogEndDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogEnd');
        const fogAttenDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogAtten');
        const fogTopDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogTop');
        const fogRangeDescriptor = Object.getOwnPropertyDescriptor(FogInfo.prototype, 'fogRange');
        apply(() => {
          displayOrder$2()(FogInfo.prototype, 'enabled', enabledDescriptor);
        }, 'displayOrder', 'enabled');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'enabled', enabledDescriptor);
        }, 'tooltip', 'enabled');
        apply(() => {
          editable$5(FogInfo.prototype);
        }, 'editable', 'enabled');
        apply(() => {
          displayOrder$2()(FogInfo.prototype, 'accurate', accurateDescriptor);
        }, 'displayOrder', 'accurate');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'accurate', accurateDescriptor);
        }, 'tooltip', 'accurate');
        apply(() => {
          editable$5(FogInfo.prototype);
        }, 'editable', 'accurate');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogColor', fogColorDescriptor);
        }, 'tooltip', 'fogColor');
        apply(() => {
          editable$5(FogInfo.prototype);
        }, 'editable', 'fogColor');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'type', typeDescriptor);
        }, 'tooltip', 'type');
        apply(() => {
          displayOrder$2()(FogInfo.prototype, 'type', typeDescriptor);
        }, 'displayOrder', 'type');
        apply(() => {
          type$a(FogType)(FogInfo.prototype, 'type', typeDescriptor);
        }, 'type', 'type');
        apply(() => {
          editable$5(FogInfo.prototype);
        }, 'editable', 'type');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogDensity', fogDensityDescriptor);
        }, 'tooltip', 'fogDensity');
        apply(() => {
          slide(FogInfo.prototype);
        }, 'slide', 'fogDensity');
        apply(() => {
          range()(FogInfo.prototype, 'fogDensity', fogDensityDescriptor);
        }, 'range', 'fogDensity');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogDensity', fogDensityDescriptor);
        }, 'type', 'fogDensity');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogDensity', fogDensityDescriptor);
        }, 'visible', 'fogDensity');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogStart', fogStartDescriptor);
        }, 'tooltip', 'fogStart');
        apply(() => {
          rangeStep()(FogInfo.prototype, 'fogStart', fogStartDescriptor);
        }, 'rangeStep', 'fogStart');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogStart', fogStartDescriptor);
        }, 'type', 'fogStart');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogStart', fogStartDescriptor);
        }, 'visible', 'fogStart');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogEnd', fogEndDescriptor);
        }, 'tooltip', 'fogEnd');
        apply(() => {
          rangeStep()(FogInfo.prototype, 'fogEnd', fogEndDescriptor);
        }, 'rangeStep', 'fogEnd');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogEnd', fogEndDescriptor);
        }, 'type', 'fogEnd');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogEnd', fogEndDescriptor);
        }, 'visible', 'fogEnd');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogAtten', fogAttenDescriptor);
        }, 'tooltip', 'fogAtten');
        apply(() => {
          rangeStep()(FogInfo.prototype, 'fogAtten', fogAttenDescriptor);
        }, 'rangeStep', 'fogAtten');
        apply(() => {
          rangeMin()(FogInfo.prototype, 'fogAtten', fogAttenDescriptor);
        }, 'rangeMin', 'fogAtten');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogAtten', fogAttenDescriptor);
        }, 'type', 'fogAtten');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogAtten', fogAttenDescriptor);
        }, 'visible', 'fogAtten');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogTop', fogTopDescriptor);
        }, 'tooltip', 'fogTop');
        apply(() => {
          rangeStep()(FogInfo.prototype, 'fogTop', fogTopDescriptor);
        }, 'rangeStep', 'fogTop');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogTop', fogTopDescriptor);
        }, 'type', 'fogTop');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogTop', fogTopDescriptor);
        }, 'visible', 'fogTop');
        apply(() => {
          tooltip$1()(FogInfo.prototype, 'fogRange', fogRangeDescriptor);
        }, 'tooltip', 'fogRange');
        apply(() => {
          rangeStep()(FogInfo.prototype, 'fogRange', fogRangeDescriptor);
        }, 'rangeStep', 'fogRange');
        apply(() => {
          type$a(CCFloat)(FogInfo.prototype, 'fogRange', fogRangeDescriptor);
        }, 'type', 'fogRange');
        apply(() => {
          visible$3()(FogInfo.prototype, 'fogRange', fogRangeDescriptor);
        }, 'visible', 'fogRange');
        apply(() => {
          serializable$l(FogInfo.prototype, '_type', () => {
            return FogType.LINEAR;
          });
        }, 'serializable', '_type');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogColor', () => {
            return new Color('#C8C8C8');
          });
        }, 'serializable', '_fogColor');
        apply(() => {
          serializable$l(FogInfo.prototype, '_enabled', () => {
            return false;
          });
        }, 'serializable', '_enabled');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogDensity', () => {
            return 0.3;
          });
        }, 'serializable', '_fogDensity');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogStart', () => {
            return 0.5;
          });
        }, 'serializable', '_fogStart');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogEnd', () => {
            return 300;
          });
        }, 'serializable', '_fogEnd');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogAtten', () => {
            return 5;
          });
        }, 'serializable', '_fogAtten');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogTop', () => {
            return 1.5;
          });
        }, 'serializable', '_fogTop');
        apply(() => {
          serializable$l(FogInfo.prototype, '_fogRange', () => {
            return 1.2;
          });
        }, 'serializable', '_fogRange');
        apply(() => {
          serializable$l(FogInfo.prototype, '_accurate', () => {
            return false;
          });
        }, 'serializable', '_accurate');
        apply(() => {
          ccclass$H('cc.FogInfo')(FogInfo);
        }, 'ccclass', null);
      }
      function patch_cc_ImageAsset(ctx, apply = defaultExec) {
        const {
          ImageAsset
        } = {
          ...ctx
        };
        const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(ImageAsset.prototype, '_nativeAsset');
        apply(() => {
          override$1(ImageAsset.prototype, '_nativeAsset', _nativeAssetDescriptor);
        }, 'override', '_nativeAsset');
        apply(() => {
          ccclass$H('cc.ImageAsset')(ImageAsset);
        }, 'ccclass', null);
      }
      function patch_cc_LightProbeInfo(ctx, apply = defaultExec) {
        const {
          LightProbeInfo,
          CCFloat,
          CCInteger
        } = {
          ...ctx
        };
        const giScaleDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'giScale');
        const giSamplesDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'giSamples');
        const bouncesDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'bounces');
        const reduceRingingDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'reduceRinging');
        const showWireframeDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'showWireframe');
        const showConvexDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'showConvex');
        const lightProbeSphereVolumeDescriptor = Object.getOwnPropertyDescriptor(LightProbeInfo.prototype, 'lightProbeSphereVolume');
        apply(() => {
          displayName$2()(LightProbeInfo.prototype, 'giScale', giScaleDescriptor);
        }, 'displayName', 'giScale');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'giScale', giScaleDescriptor);
        }, 'tooltip', 'giScale');
        apply(() => {
          type$a(CCFloat)(LightProbeInfo.prototype, 'giScale', giScaleDescriptor);
        }, 'type', 'giScale');
        apply(() => {
          range()(LightProbeInfo.prototype, 'giScale', giScaleDescriptor);
        }, 'range', 'giScale');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'giScale');
        apply(() => {
          displayName$2()(LightProbeInfo.prototype, 'giSamples', giSamplesDescriptor);
        }, 'displayName', 'giSamples');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'giSamples', giSamplesDescriptor);
        }, 'tooltip', 'giSamples');
        apply(() => {
          type$a(CCInteger)(LightProbeInfo.prototype, 'giSamples', giSamplesDescriptor);
        }, 'type', 'giSamples');
        apply(() => {
          range()(LightProbeInfo.prototype, 'giSamples', giSamplesDescriptor);
        }, 'range', 'giSamples');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'giSamples');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'bounces', bouncesDescriptor);
        }, 'tooltip', 'bounces');
        apply(() => {
          type$a(CCInteger)(LightProbeInfo.prototype, 'bounces', bouncesDescriptor);
        }, 'type', 'bounces');
        apply(() => {
          range()(LightProbeInfo.prototype, 'bounces', bouncesDescriptor);
        }, 'range', 'bounces');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'bounces');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor);
        }, 'tooltip', 'reduceRinging');
        apply(() => {
          type$a(CCFloat)(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor);
        }, 'type', 'reduceRinging');
        apply(() => {
          slide(LightProbeInfo.prototype);
        }, 'slide', 'reduceRinging');
        apply(() => {
          range()(LightProbeInfo.prototype, 'reduceRinging', reduceRingingDescriptor);
        }, 'range', 'reduceRinging');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'reduceRinging');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'showWireframe', showWireframeDescriptor);
        }, 'tooltip', 'showWireframe');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'showWireframe');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'showConvex', showConvexDescriptor);
        }, 'tooltip', 'showConvex');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'showConvex');
        apply(() => {
          tooltip$1()(LightProbeInfo.prototype, 'lightProbeSphereVolume', lightProbeSphereVolumeDescriptor);
        }, 'tooltip', 'lightProbeSphereVolume');
        apply(() => {
          type$a(CCFloat)(LightProbeInfo.prototype, 'lightProbeSphereVolume', lightProbeSphereVolumeDescriptor);
        }, 'type', 'lightProbeSphereVolume');
        apply(() => {
          range()(LightProbeInfo.prototype, 'lightProbeSphereVolume', lightProbeSphereVolumeDescriptor);
        }, 'range', 'lightProbeSphereVolume');
        apply(() => {
          editable$5(LightProbeInfo.prototype);
        }, 'editable', 'lightProbeSphereVolume');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_giScale', () => {
            return 1.0;
          });
        }, 'serializable', '_giScale');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_giSamples', () => {
            return 1024;
          });
        }, 'serializable', '_giSamples');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_bounces', () => {
            return 2;
          });
        }, 'serializable', '_bounces');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_reduceRinging', () => {
            return 0.0;
          });
        }, 'serializable', '_reduceRinging');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_showProbe', () => {
            return true;
          });
        }, 'serializable', '_showProbe');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_showWireframe', () => {
            return true;
          });
        }, 'serializable', '_showWireframe');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_showConvex', () => {
            return false;
          });
        }, 'serializable', '_showConvex');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_data', () => {
            return null;
          });
        }, 'serializable', '_data');
        apply(() => {
          serializable$l(LightProbeInfo.prototype, '_lightProbeSphereVolume', () => {
            return 1.0;
          });
        }, 'serializable', '_lightProbeSphereVolume');
        apply(() => {
          ccclass$H('cc.LightProbeInfo')(LightProbeInfo);
        }, 'ccclass', null);
      }
      function patch_cc_LightProbesData(ctx, apply = defaultExec) {
        const {
          LightProbesData,
          Vertex,
          Tetrahedron
        } = {
          ...ctx
        };
        apply(() => {
          type$a([Vertex])(LightProbesData.prototype, '_probes', () => {
            return [];
          });
        }, 'type', '_probes');
        apply(() => {
          serializable$l(LightProbesData.prototype, '_probes', () => {
            return [];
          });
        }, 'serializable', '_probes');
        apply(() => {
          type$a([Tetrahedron])(LightProbesData.prototype, '_tetrahedrons', () => {
            return [];
          });
        }, 'type', '_tetrahedrons');
        apply(() => {
          serializable$l(LightProbesData.prototype, '_tetrahedrons', () => {
            return [];
          });
        }, 'serializable', '_tetrahedrons');
        apply(() => {
          ccclass$H('cc.LightProbesData')(LightProbesData);
        }, 'ccclass', null);
      }
      function patch_cc_Material(ctx, apply = defaultExec) {
        const {
          Material,
          EffectAsset
        } = {
          ...ctx
        };
        apply(() => {
          type$a(EffectAsset)(Material.prototype, '_effectAsset', () => {
            return null;
          });
        }, 'type', '_effectAsset');
        apply(() => {
          serializable$l(Material.prototype, '_techIdx', () => {
            return 0;
          });
        }, 'serializable', '_techIdx');
        apply(() => {
          serializable$l(Material.prototype, '_defines', () => {
            return [];
          });
        }, 'serializable', '_defines');
        apply(() => {
          serializable$l(Material.prototype, '_states', () => {
            return [];
          });
        }, 'serializable', '_states');
        apply(() => {
          serializable$l(Material.prototype, '_props', () => {
            return [];
          });
        }, 'serializable', '_props');
        apply(() => {
          ccclass$H('cc.Material')(Material);
        }, 'ccclass', null);
      }
      function patch_cc_Mesh(ctx, apply = defaultExec) {
        const {
          Mesh
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(Mesh.prototype, '_struct', () => {
            return {
              vertexBundles: [],
              primitives: []
            };
          });
        }, 'serializable', '_struct');
        apply(() => {
          serializable$l(Mesh.prototype, '_hash', () => {
            return 0;
          });
        }, 'serializable', '_hash');
        apply(() => {
          serializable$l(Mesh.prototype, '_allowDataAccess', () => {
            return true;
          });
        }, 'serializable', '_allowDataAccess');
        apply(() => {
          ccclass$H('cc.Mesh')(Mesh);
        }, 'ccclass', null);
      }
      function patch_cc_Node(ctx, apply = defaultExec) {
        const {
          Node,
          Vec3,
          Quat,
          MobilityMode,
          Layers
        } = {
          ...ctx
        };
        const _persistNodeDescriptor = Object.getOwnPropertyDescriptor(Node.prototype, '_persistNode');
        Object.getOwnPropertyDescriptor(Node.prototype, 'name');
        Object.getOwnPropertyDescriptor(Node.prototype, 'children');
        Object.getOwnPropertyDescriptor(Node.prototype, 'active');
        Object.getOwnPropertyDescriptor(Node.prototype, 'activeInHierarchy');
        Object.getOwnPropertyDescriptor(Node.prototype, 'parent');
        const eulerAnglesDescriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'eulerAngles');
        Object.getOwnPropertyDescriptor(Node.prototype, 'angle');
        const mobilityDescriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'mobility');
        Object.getOwnPropertyDescriptor(Node.prototype, 'layer');
        apply(() => {
          property(Node.prototype, '_persistNode', _persistNodeDescriptor);
        }, 'property', '_persistNode');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'name');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'children');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'active');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'activeInHierarchy');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'parent');
        apply(() => {
          serializable$l(Node.prototype, '_parent', () => {
            return null;
          });
        }, 'serializable', '_parent');
        apply(() => {
          serializable$l(Node.prototype, '_children', () => {
            return [];
          });
        }, 'serializable', '_children');
        apply(() => {
          serializable$l(Node.prototype, '_active', () => {
            return true;
          });
        }, 'serializable', '_active');
        apply(() => {
          serializable$l(Node.prototype, '_components', () => {
            return [];
          });
        }, 'serializable', '_components');
        apply(() => {
          serializable$l(Node.prototype, '_prefab', () => {
            return null;
          });
        }, 'serializable', '_prefab');
        apply(() => {
          serializable$l(Node.prototype, '_lpos', () => {
            return new Vec3();
          });
        }, 'serializable', '_lpos');
        apply(() => {
          serializable$l(Node.prototype, '_lrot', () => {
            return new Quat();
          });
        }, 'serializable', '_lrot');
        apply(() => {
          serializable$l(Node.prototype, '_lscale', () => {
            return new Vec3(1, 1, 1);
          });
        }, 'serializable', '_lscale');
        apply(() => {
          serializable$l(Node.prototype, '_mobility', () => {
            return MobilityMode.Static;
          });
        }, 'serializable', '_mobility');
        apply(() => {
          serializable$l(Node.prototype, '_layer', () => {
            return Layers.Enum.DEFAULT;
          });
        }, 'serializable', '_layer');
        apply(() => {
          serializable$l(Node.prototype, '_euler', () => {
            return new Vec3();
          });
        }, 'serializable', '_euler');
        apply(() => {
          type$a(Vec3)(Node.prototype, 'eulerAngles', eulerAnglesDescriptor);
        }, 'type', 'eulerAngles');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'angle');
        apply(() => {
          type$a(MobilityMode)(Node.prototype, 'mobility', mobilityDescriptor);
        }, 'type', 'mobility');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'mobility');
        apply(() => {
          editable$5(Node.prototype);
        }, 'editable', 'layer');
        apply(() => {
          ccclass$H('cc.Node')(Node);
        }, 'ccclass', null);
      }
      function patch_cc_OctreeInfo(ctx, apply = defaultExec) {
        const {
          OctreeInfo,
          CCInteger,
          Vec3,
          DEFAULT_WORLD_MIN_POS,
          DEFAULT_WORLD_MAX_POS,
          DEFAULT_OCTREE_DEPTH
        } = {
          ...ctx
        };
        const enabledDescriptor = Object.getOwnPropertyDescriptor(OctreeInfo.prototype, 'enabled');
        const minPosDescriptor = Object.getOwnPropertyDescriptor(OctreeInfo.prototype, 'minPos');
        const maxPosDescriptor = Object.getOwnPropertyDescriptor(OctreeInfo.prototype, 'maxPos');
        const depthDescriptor = Object.getOwnPropertyDescriptor(OctreeInfo.prototype, 'depth');
        apply(() => {
          tooltip$1()(OctreeInfo.prototype, 'enabled', enabledDescriptor);
        }, 'tooltip', 'enabled');
        apply(() => {
          editable$5(OctreeInfo.prototype);
        }, 'editable', 'enabled');
        apply(() => {
          displayName$2()(OctreeInfo.prototype, 'minPos', minPosDescriptor);
        }, 'displayName', 'minPos');
        apply(() => {
          tooltip$1()(OctreeInfo.prototype, 'minPos', minPosDescriptor);
        }, 'tooltip', 'minPos');
        apply(() => {
          editable$5(OctreeInfo.prototype);
        }, 'editable', 'minPos');
        apply(() => {
          displayName$2()(OctreeInfo.prototype, 'maxPos', maxPosDescriptor);
        }, 'displayName', 'maxPos');
        apply(() => {
          tooltip$1()(OctreeInfo.prototype, 'maxPos', maxPosDescriptor);
        }, 'tooltip', 'maxPos');
        apply(() => {
          editable$5(OctreeInfo.prototype);
        }, 'editable', 'maxPos');
        apply(() => {
          tooltip$1()(OctreeInfo.prototype, 'depth', depthDescriptor);
        }, 'tooltip', 'depth');
        apply(() => {
          type$a(CCInteger)(OctreeInfo.prototype, 'depth', depthDescriptor);
        }, 'type', 'depth');
        apply(() => {
          slide(OctreeInfo.prototype);
        }, 'slide', 'depth');
        apply(() => {
          range()(OctreeInfo.prototype, 'depth', depthDescriptor);
        }, 'range', 'depth');
        apply(() => {
          editable$5(OctreeInfo.prototype);
        }, 'editable', 'depth');
        apply(() => {
          serializable$l(OctreeInfo.prototype, '_enabled', () => {
            return false;
          });
        }, 'serializable', '_enabled');
        apply(() => {
          serializable$l(OctreeInfo.prototype, '_minPos', () => {
            return new Vec3(DEFAULT_WORLD_MIN_POS);
          });
        }, 'serializable', '_minPos');
        apply(() => {
          serializable$l(OctreeInfo.prototype, '_maxPos', () => {
            return new Vec3(DEFAULT_WORLD_MAX_POS);
          });
        }, 'serializable', '_maxPos');
        apply(() => {
          serializable$l(OctreeInfo.prototype, '_depth', () => {
            return DEFAULT_OCTREE_DEPTH;
          });
        }, 'serializable', '_depth');
        apply(() => {
          ccclass$H('cc.OctreeInfo')(OctreeInfo);
        }, 'ccclass', null);
      }
      function patch_cc_PostSettingsInfo(ctx, apply = defaultExec) {
        const {
          PostSettingsInfo,
          ToneMappingType
        } = {
          ...ctx
        };
        const toneMappingTypeDescriptor = Object.getOwnPropertyDescriptor(PostSettingsInfo.prototype, 'toneMappingType');
        apply(() => {
          tooltip$1()(PostSettingsInfo.prototype, 'toneMappingType', toneMappingTypeDescriptor);
        }, 'tooltip', 'toneMappingType');
        apply(() => {
          type$a(ToneMappingType)(PostSettingsInfo.prototype, 'toneMappingType', toneMappingTypeDescriptor);
        }, 'type', 'toneMappingType');
        apply(() => {
          editable$5(PostSettingsInfo.prototype);
        }, 'editable', 'toneMappingType');
        apply(() => {
          serializable$l(PostSettingsInfo.prototype, '_toneMappingType', () => {
            return ToneMappingType.DEFAULT;
          });
        }, 'serializable', '_toneMappingType');
        apply(() => {
          ccclass$H('cc.PostSettingsInfo')(PostSettingsInfo);
        }, 'ccclass', null);
      }
      function patch_cc_RenderPipeline(ctx, apply = defaultExec) {
        const {
          RenderPipeline,
          RenderFlow
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(RenderPipeline.prototype, '_tag', () => {
            return 0;
          });
        }, 'serializable', '_tag');
        apply(() => {
          displayOrder$2()(RenderPipeline.prototype, '_tag', () => {
            return 0;
          });
        }, 'displayOrder', '_tag');
        apply(() => {
          serializable$l(RenderPipeline.prototype, '_flows', () => {
            return [];
          });
        }, 'serializable', '_flows');
        apply(() => {
          type$a([RenderFlow])(RenderPipeline.prototype, '_flows', () => {
            return [];
          });
        }, 'type', '_flows');
        apply(() => {
          displayOrder$2()(RenderPipeline.prototype, '_flows', () => {
            return [];
          });
        }, 'displayOrder', '_flows');
        apply(() => {
          ccclass$H('cc.RenderPipeline')(RenderPipeline);
        }, 'ccclass', null);
      }
      function patch_cc_RenderTexture(ctx, apply = defaultExec) {
        const {
          RenderTexture
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('cc.RenderTexture')(RenderTexture);
        }, 'ccclass', null);
      }
      function patch_cc_Scene(ctx, apply = defaultExec) {
        const {
          Scene,
          SceneGlobals
        } = {
          ...ctx
        };
        Object.getOwnPropertyDescriptor(Scene.prototype, 'globals');
        apply(() => {
          editable$5(Scene.prototype);
        }, 'editable', 'globals');
        apply(() => {
          editable$5(Scene.prototype);
        }, 'editable', 'autoReleaseAssets');
        apply(() => {
          serializable$l(Scene.prototype, 'autoReleaseAssets', () => {
            return false;
          });
        }, 'serializable', 'autoReleaseAssets');
        apply(() => {
          serializable$l(Scene.prototype, '_globals', () => {
            return new SceneGlobals();
          });
        }, 'serializable', '_globals');
        apply(() => {
          ccclass$H('cc.Scene')(Scene);
        }, 'ccclass', null);
      }
      function patch_cc_SceneAsset(ctx, apply = defaultExec) {
        const {
          SceneAsset
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(SceneAsset.prototype, 'scene', () => {
            return null;
          });
        }, 'serializable', 'scene');
        apply(() => {
          editable$5(SceneAsset.prototype);
        }, 'editable', 'scene');
        apply(() => {
          ccclass$H('cc.SceneAsset')(SceneAsset);
        }, 'ccclass', null);
      }
      function patch_cc_SceneGlobals(ctx, apply = defaultExec) {
        const {
          SceneGlobals,
          AmbientInfo,
          ShadowsInfo,
          SkyboxInfo,
          FogInfo,
          OctreeInfo,
          SkinInfo,
          LightProbeInfo,
          PostSettingsInfo
        } = {
          ...ctx
        };
        const skyboxDescriptor = Object.getOwnPropertyDescriptor(SceneGlobals.prototype, 'skybox');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'ambient');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'ambient', () => {
            return new AmbientInfo();
          });
        }, 'serializable', 'ambient');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'shadows');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'shadows', () => {
            return new ShadowsInfo();
          });
        }, 'serializable', 'shadows');
        apply(() => {
          serializable$l(SceneGlobals.prototype, '_skybox', () => {
            return new SkyboxInfo();
          });
        }, 'serializable', '_skybox');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'fog', () => {
            return new FogInfo();
          });
        }, 'serializable', 'fog');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'fog');
        apply(() => {
          type$a(SkyboxInfo)(SceneGlobals.prototype, 'skybox', skyboxDescriptor);
        }, 'type', 'skybox');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'skybox');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'octree', () => {
            return new OctreeInfo();
          });
        }, 'serializable', 'octree');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'octree');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'skin', () => {
            return new SkinInfo();
          });
        }, 'serializable', 'skin');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'skin');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'lightProbeInfo', () => {
            return new LightProbeInfo();
          });
        }, 'serializable', 'lightProbeInfo');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'lightProbeInfo');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'postSettings', () => {
            return new PostSettingsInfo();
          });
        }, 'serializable', 'postSettings');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'postSettings');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'bakedWithStationaryMainLight', () => {
            return false;
          });
        }, 'serializable', 'bakedWithStationaryMainLight');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'bakedWithStationaryMainLight');
        apply(() => {
          serializable$l(SceneGlobals.prototype, 'bakedWithHighpLightmap', () => {
            return false;
          });
        }, 'serializable', 'bakedWithHighpLightmap');
        apply(() => {
          editable$5(SceneGlobals.prototype);
        }, 'editable', 'bakedWithHighpLightmap');
        apply(() => {
          ccclass$H('cc.SceneGlobals')(SceneGlobals);
        }, 'ccclass', null);
      }
      function patch_cc_ShadowsInfo(ctx, apply = defaultExec) {
        const {
          ShadowsInfo,
          ShadowType,
          CCFloat,
          CCInteger,
          ShadowSize,
          Vec3,
          Color,
          Vec2
        } = {
          ...ctx
        };
        const enabledDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'enabled');
        const typeDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'type');
        const shadowColorDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'shadowColor');
        const planeDirectionDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'planeDirection');
        const planeHeightDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'planeHeight');
        const planeBiasDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'planeBias');
        const maxReceivedDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'maxReceived');
        const shadowMapSizeDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfo.prototype, 'shadowMapSize');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'enabled', enabledDescriptor);
        }, 'tooltip', 'enabled');
        apply(() => {
          editable$5(ShadowsInfo.prototype);
        }, 'editable', 'enabled');
        apply(() => {
          type$a(ShadowType)(ShadowsInfo.prototype, 'type', typeDescriptor);
        }, 'type', 'type');
        apply(() => {
          editable$5(ShadowsInfo.prototype);
        }, 'editable', 'type');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'type', typeDescriptor);
        }, 'tooltip', 'type');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'shadowColor', shadowColorDescriptor);
        }, 'visible', 'shadowColor');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'shadowColor', shadowColorDescriptor);
        }, 'tooltip', 'shadowColor');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'planeDirection', planeDirectionDescriptor);
        }, 'visible', 'planeDirection');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'planeDirection', planeDirectionDescriptor);
        }, 'tooltip', 'planeDirection');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'planeHeight', planeHeightDescriptor);
        }, 'visible', 'planeHeight');
        apply(() => {
          type$a(CCFloat)(ShadowsInfo.prototype, 'planeHeight', planeHeightDescriptor);
        }, 'type', 'planeHeight');
        apply(() => {
          editable$5(ShadowsInfo.prototype);
        }, 'editable', 'planeHeight');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'planeHeight', planeHeightDescriptor);
        }, 'tooltip', 'planeHeight');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'planeBias', planeBiasDescriptor);
        }, 'visible', 'planeBias');
        apply(() => {
          type$a(CCFloat)(ShadowsInfo.prototype, 'planeBias', planeBiasDescriptor);
        }, 'type', 'planeBias');
        apply(() => {
          editable$5(ShadowsInfo.prototype);
        }, 'editable', 'planeBias');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'planeBias', planeBiasDescriptor);
        }, 'tooltip', 'planeBias');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'maxReceived', maxReceivedDescriptor);
        }, 'visible', 'maxReceived');
        apply(() => {
          type$a(CCInteger)(ShadowsInfo.prototype, 'maxReceived', maxReceivedDescriptor);
        }, 'type', 'maxReceived');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'maxReceived', maxReceivedDescriptor);
        }, 'tooltip', 'maxReceived');
        apply(() => {
          visible$3()(ShadowsInfo.prototype, 'shadowMapSize', shadowMapSizeDescriptor);
        }, 'visible', 'shadowMapSize');
        apply(() => {
          type$a(ShadowSize)(ShadowsInfo.prototype, 'shadowMapSize', shadowMapSizeDescriptor);
        }, 'type', 'shadowMapSize');
        apply(() => {
          tooltip$1()(ShadowsInfo.prototype, 'shadowMapSize', shadowMapSizeDescriptor);
        }, 'tooltip', 'shadowMapSize');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_enabled', () => {
            return false;
          });
        }, 'serializable', '_enabled');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_type', () => {
            return ShadowType.Planar;
          });
        }, 'serializable', '_type');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_normal', () => {
            return new Vec3(0, 1, 0);
          });
        }, 'serializable', '_normal');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_distance', () => {
            return 0;
          });
        }, 'serializable', '_distance');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_planeBias', () => {
            return 1.0;
          });
        }, 'serializable', '_planeBias');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_shadowColor', () => {
            return new Color(0, 0, 0, 76);
          });
        }, 'serializable', '_shadowColor');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_maxReceived', () => {
            return 4;
          });
        }, 'serializable', '_maxReceived');
        apply(() => {
          serializable$l(ShadowsInfo.prototype, '_size', () => {
            return new Vec2(1024, 1024);
          });
        }, 'serializable', '_size');
        apply(() => {
          ccclass$H('cc.ShadowsInfo')(ShadowsInfo);
        }, 'ccclass', null);
      }
      function patch_cc_SimpleTexture(ctx, apply = defaultExec) {
        const {
          SimpleTexture
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('cc.SimpleTexture')(SimpleTexture);
        }, 'ccclass', null);
      }
      function patch_cc_Skeleton(ctx, apply = defaultExec) {
        const {
          Skeleton,
          CCString,
          Mat4
        } = {
          ...ctx
        };
        apply(() => {
          type$a([CCString])(Skeleton.prototype, '_joints', () => {
            return [];
          });
        }, 'type', '_joints');
        apply(() => {
          type$a([Mat4])(Skeleton.prototype, '_bindposes', () => {
            return [];
          });
        }, 'type', '_bindposes');
        apply(() => {
          serializable$l(Skeleton.prototype, '_hash', () => {
            return 0;
          });
        }, 'serializable', '_hash');
        apply(() => {
          ccclass$H('cc.Skeleton')(Skeleton);
        }, 'ccclass', null);
      }
      function patch_cc_SkinInfo(ctx, apply = defaultExec) {
        const {
          SkinInfo,
          CCFloat
        } = {
          ...ctx
        };
        const enabledDescriptor = Object.getOwnPropertyDescriptor(SkinInfo.prototype, 'enabled');
        const blurRadiusDescriptor = Object.getOwnPropertyDescriptor(SkinInfo.prototype, 'blurRadius');
        const sssIntensityDescriptor = Object.getOwnPropertyDescriptor(SkinInfo.prototype, 'sssIntensity');
        apply(() => {
          tooltip$1()(SkinInfo.prototype, 'enabled', enabledDescriptor);
        }, 'tooltip', 'enabled');
        apply(() => {
          readOnly(SkinInfo.prototype);
        }, 'readOnly', 'enabled');
        apply(() => {
          editable$5(SkinInfo.prototype);
        }, 'editable', 'enabled');
        apply(() => {
          tooltip$1()(SkinInfo.prototype, 'blurRadius', blurRadiusDescriptor);
        }, 'tooltip', 'blurRadius');
        apply(() => {
          type$a(CCFloat)(SkinInfo.prototype, 'blurRadius', blurRadiusDescriptor);
        }, 'type', 'blurRadius');
        apply(() => {
          slide(SkinInfo.prototype);
        }, 'slide', 'blurRadius');
        apply(() => {
          range()(SkinInfo.prototype, 'blurRadius', blurRadiusDescriptor);
        }, 'range', 'blurRadius');
        apply(() => {
          editable$5(SkinInfo.prototype);
        }, 'editable', 'blurRadius');
        apply(() => {
          visible$3()(SkinInfo.prototype, 'blurRadius', blurRadiusDescriptor);
        }, 'visible', 'blurRadius');
        apply(() => {
          tooltip$1()(SkinInfo.prototype, 'sssIntensity', sssIntensityDescriptor);
        }, 'tooltip', 'sssIntensity');
        apply(() => {
          type$a(CCFloat)(SkinInfo.prototype, 'sssIntensity', sssIntensityDescriptor);
        }, 'type', 'sssIntensity');
        apply(() => {
          slide(SkinInfo.prototype);
        }, 'slide', 'sssIntensity');
        apply(() => {
          range()(SkinInfo.prototype, 'sssIntensity', sssIntensityDescriptor);
        }, 'range', 'sssIntensity');
        apply(() => {
          editable$5(SkinInfo.prototype);
        }, 'editable', 'sssIntensity');
        apply(() => {
          serializable$l(SkinInfo.prototype, '_enabled', () => {
            return true;
          });
        }, 'serializable', '_enabled');
        apply(() => {
          serializable$l(SkinInfo.prototype, '_blurRadius', () => {
            return 0.01;
          });
        }, 'serializable', '_blurRadius');
        apply(() => {
          serializable$l(SkinInfo.prototype, '_sssIntensity', () => {
            return 3.0;
          });
        }, 'serializable', '_sssIntensity');
        apply(() => {
          ccclass$H('cc.SkinInfo')(SkinInfo);
        }, 'ccclass', null);
      }
      function patch_cc_SkyboxInfo(ctx, apply = defaultExec) {
        const {
          SkyboxInfo,
          EnvironmentLightingType,
          TextureCube,
          CCFloat,
          Material
        } = {
          ...ctx
        };
        const enabledDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'enabled');
        const envLightingTypeDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'envLightingType');
        const useHDRDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'useHDR');
        const envmapDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'envmap');
        const rotationAngleDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'rotationAngle');
        const diffuseMapDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'diffuseMap');
        const reflectionMapDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'reflectionMap');
        const skyboxMaterialDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfo.prototype, 'skyboxMaterial');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'enabled', enabledDescriptor);
        }, 'tooltip', 'enabled');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'enabled');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'envLightingType', envLightingTypeDescriptor);
        }, 'tooltip', 'envLightingType');
        apply(() => {
          type$a(EnvironmentLightingType)(SkyboxInfo.prototype, 'envLightingType', envLightingTypeDescriptor);
        }, 'type', 'envLightingType');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'envLightingType');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'useHDR', useHDRDescriptor);
        }, 'tooltip', 'useHDR');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'useHDR');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'envmap', envmapDescriptor);
        }, 'tooltip', 'envmap');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, 'envmap', envmapDescriptor);
        }, 'type', 'envmap');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'envmap');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'rotationAngle', rotationAngleDescriptor);
        }, 'tooltip', 'rotationAngle');
        apply(() => {
          slide(SkyboxInfo.prototype);
        }, 'slide', 'rotationAngle');
        apply(() => {
          range()(SkyboxInfo.prototype, 'rotationAngle', rotationAngleDescriptor);
        }, 'range', 'rotationAngle');
        apply(() => {
          type$a(CCFloat)(SkyboxInfo.prototype, 'rotationAngle', rotationAngleDescriptor);
        }, 'type', 'rotationAngle');
        apply(() => {
          displayOrder$2()(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor);
        }, 'displayOrder', 'diffuseMap');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor);
        }, 'type', 'diffuseMap');
        apply(() => {
          readOnly(SkyboxInfo.prototype);
        }, 'readOnly', 'diffuseMap');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'diffuseMap');
        apply(() => {
          visible$3()(SkyboxInfo.prototype, 'diffuseMap', diffuseMapDescriptor);
        }, 'visible', 'diffuseMap');
        apply(() => {
          displayOrder$2()(SkyboxInfo.prototype, 'reflectionMap', reflectionMapDescriptor);
        }, 'displayOrder', 'reflectionMap');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, 'reflectionMap', reflectionMapDescriptor);
        }, 'type', 'reflectionMap');
        apply(() => {
          readOnly(SkyboxInfo.prototype);
        }, 'readOnly', 'reflectionMap');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'reflectionMap');
        apply(() => {
          visible$3()(SkyboxInfo.prototype, 'reflectionMap', reflectionMapDescriptor);
        }, 'visible', 'reflectionMap');
        apply(() => {
          tooltip$1()(SkyboxInfo.prototype, 'skyboxMaterial', skyboxMaterialDescriptor);
        }, 'tooltip', 'skyboxMaterial');
        apply(() => {
          type$a(Material)(SkyboxInfo.prototype, 'skyboxMaterial', skyboxMaterialDescriptor);
        }, 'type', 'skyboxMaterial');
        apply(() => {
          editable$5(SkyboxInfo.prototype);
        }, 'editable', 'skyboxMaterial');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_envLightingType', () => {
            return 0;
          });
        }, 'serializable', '_envLightingType');
        apply(() => {
          formerlySerializedAs$2('_envmap')(SkyboxInfo.prototype, '_envmapHDR', () => {
            return null;
          });
        }, 'formerlySerializedAs', '_envmapHDR');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_envmapHDR', () => {
            return null;
          });
        }, 'type', '_envmapHDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_envmapHDR', () => {
            return null;
          });
        }, 'serializable', '_envmapHDR');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_envmapLDR', () => {
            return null;
          });
        }, 'type', '_envmapLDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_envmapLDR', () => {
            return null;
          });
        }, 'serializable', '_envmapLDR');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_diffuseMapHDR', () => {
            return null;
          });
        }, 'type', '_diffuseMapHDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_diffuseMapHDR', () => {
            return null;
          });
        }, 'serializable', '_diffuseMapHDR');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_diffuseMapLDR', () => {
            return null;
          });
        }, 'type', '_diffuseMapLDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_diffuseMapLDR', () => {
            return null;
          });
        }, 'serializable', '_diffuseMapLDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_enabled', () => {
            return false;
          });
        }, 'serializable', '_enabled');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_useHDR', () => {
            return true;
          });
        }, 'serializable', '_useHDR');
        apply(() => {
          type$a(Material)(SkyboxInfo.prototype, '_editableMaterial', () => {
            return null;
          });
        }, 'type', '_editableMaterial');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_editableMaterial', () => {
            return null;
          });
        }, 'serializable', '_editableMaterial');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_reflectionHDR', () => {
            return null;
          });
        }, 'type', '_reflectionHDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_reflectionHDR', () => {
            return null;
          });
        }, 'serializable', '_reflectionHDR');
        apply(() => {
          type$a(TextureCube)(SkyboxInfo.prototype, '_reflectionLDR', () => {
            return null;
          });
        }, 'type', '_reflectionLDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_reflectionLDR', () => {
            return null;
          });
        }, 'serializable', '_reflectionLDR');
        apply(() => {
          serializable$l(SkyboxInfo.prototype, '_rotationAngle', () => {
            return 0;
          });
        }, 'serializable', '_rotationAngle');
        apply(() => {
          ccclass$H('cc.SkyboxInfo')(SkyboxInfo);
        }, 'ccclass', null);
      }
      function patch_cc_Tetrahedron(ctx, apply = defaultExec) {
        const {
          Tetrahedron,
          Mat3,
          Vec3,
          CircumSphere
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'invalid', () => {
            return false;
          });
        }, 'serializable', 'invalid');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'vertex0', () => {
            return -1;
          });
        }, 'serializable', 'vertex0');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'vertex1', () => {
            return -1;
          });
        }, 'serializable', 'vertex1');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'vertex2', () => {
            return -1;
          });
        }, 'serializable', 'vertex2');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'vertex3', () => {
            return -1;
          });
        }, 'serializable', 'vertex3');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'neighbours', () => {
            return [-1, -1, -1, -1];
          });
        }, 'serializable', 'neighbours');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'matrix', () => {
            return new Mat3();
          });
        }, 'serializable', 'matrix');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'offset', () => {
            return new Vec3(0.0, 0.0, 0.0);
          });
        }, 'serializable', 'offset');
        apply(() => {
          serializable$l(Tetrahedron.prototype, 'sphere', () => {
            return new CircumSphere();
          });
        }, 'serializable', 'sphere');
        apply(() => {
          ccclass$H('cc.Tetrahedron')(Tetrahedron);
        }, 'ccclass', null);
      }
      function patch_cc_Texture2D(ctx, apply = defaultExec) {
        const {
          Texture2D,
          ImageAsset
        } = {
          ...ctx
        };
        apply(() => {
          type$a([ImageAsset])(Texture2D.prototype, '_mipmaps', () => {
            return [];
          });
        }, 'type', '_mipmaps');
        apply(() => {
          ccclass$H('cc.Texture2D')(Texture2D);
        }, 'ccclass', null);
      }
      function patch_cc_TextureBase(ctx, apply = defaultExec) {
        const {
          TextureBase,
          PixelFormat,
          Filter,
          WrapMode
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(TextureBase.prototype, '_format', () => {
            return 35;
          });
        }, 'serializable', '_format');
        apply(() => {
          serializable$l(TextureBase.prototype, '_minFilter', () => {
            return 2;
          });
        }, 'serializable', '_minFilter');
        apply(() => {
          serializable$l(TextureBase.prototype, '_magFilter', () => {
            return 2;
          });
        }, 'serializable', '_magFilter');
        apply(() => {
          serializable$l(TextureBase.prototype, '_mipFilter', () => {
            return 0;
          });
        }, 'serializable', '_mipFilter');
        apply(() => {
          serializable$l(TextureBase.prototype, '_wrapS', () => {
            return 0;
          });
        }, 'serializable', '_wrapS');
        apply(() => {
          serializable$l(TextureBase.prototype, '_wrapT', () => {
            return 0;
          });
        }, 'serializable', '_wrapT');
        apply(() => {
          serializable$l(TextureBase.prototype, '_wrapR', () => {
            return 0;
          });
        }, 'serializable', '_wrapR');
        apply(() => {
          serializable$l(TextureBase.prototype, '_anisotropy', () => {
            return 0;
          });
        }, 'serializable', '_anisotropy');
        apply(() => {
          ccclass$H('cc.TextureBase')(TextureBase);
        }, 'ccclass', null);
      }
      function patch_cc_TextureCube(ctx, apply = defaultExec) {
        const {
          TextureCube,
          MipmapMode
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(TextureCube.prototype, 'isRGBE', () => {
            return false;
          });
        }, 'serializable', 'isRGBE');
        apply(() => {
          serializable$l(TextureCube.prototype, '_mipmapAtlas', () => {
            return null;
          });
        }, 'serializable', '_mipmapAtlas');
        apply(() => {
          serializable$l(TextureCube.prototype, '_mipmapMode', () => {
            return 0;
          });
        }, 'serializable', '_mipmapMode');
        apply(() => {
          serializable$l(TextureCube.prototype, '_mipmaps', () => {
            return [];
          });
        }, 'serializable', '_mipmaps');
        apply(() => {
          ccclass$H('cc.TextureCube')(TextureCube);
        }, 'ccclass', null);
      }
      function patch_cc_Vertex(ctx, apply = defaultExec) {
        const {
          Vertex,
          Vec3
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(Vertex.prototype, 'position', () => {
            return new Vec3(0, 0, 0);
          });
        }, 'serializable', 'position');
        apply(() => {
          serializable$l(Vertex.prototype, 'normal', () => {
            return new Vec3(0, 0, 0);
          });
        }, 'serializable', 'normal');
        apply(() => {
          serializable$l(Vertex.prototype, 'coefficients', () => {
            return [];
          });
        }, 'serializable', 'coefficients');
        apply(() => {
          ccclass$H('cc.Vertex')(Vertex);
        }, 'ccclass', null);
      }
      function patch_DeferredPipeline(ctx, apply = defaultExec) {
        const {
          DeferredPipeline,
          RenderTextureConfig
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(DeferredPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'displayOrder', 'renderTextures');
        apply(() => {
          serializable$l(DeferredPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'serializable', 'renderTextures');
        apply(() => {
          type$a([RenderTextureConfig])(DeferredPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'type', 'renderTextures');
        apply(() => {
          ccclass$H('DeferredPipeline')(DeferredPipeline);
        }, 'ccclass', null);
      }
      function patch_ForwardFlow(ctx, apply = defaultExec) {
        const {
          ForwardFlow
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('ForwardFlow')(ForwardFlow);
        }, 'ccclass', null);
      }
      function patch_ForwardPipeline(ctx, apply = defaultExec) {
        const {
          ForwardPipeline,
          RenderTextureConfig
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(ForwardPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'displayOrder', 'renderTextures');
        apply(() => {
          serializable$l(ForwardPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'serializable', 'renderTextures');
        apply(() => {
          type$a([RenderTextureConfig])(ForwardPipeline.prototype, 'renderTextures', () => {
            return [];
          });
        }, 'type', 'renderTextures');
        apply(() => {
          ccclass$H('ForwardPipeline')(ForwardPipeline);
        }, 'ccclass', null);
      }
      function patch_ForwardStage(ctx, apply = defaultExec) {
        const {
          ForwardStage,
          RenderQueueDesc
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(ForwardStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'displayOrder', 'renderQueues');
        apply(() => {
          serializable$l(ForwardStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'serializable', 'renderQueues');
        apply(() => {
          type$a([RenderQueueDesc])(ForwardStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'type', 'renderQueues');
        apply(() => {
          ccclass$H('ForwardStage')(ForwardStage);
        }, 'ccclass', null);
      }
      function patch_GbufferStage(ctx, apply = defaultExec) {
        const {
          GbufferStage,
          RenderQueueDesc
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(GbufferStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'displayOrder', 'renderQueues');
        apply(() => {
          serializable$l(GbufferStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'serializable', 'renderQueues');
        apply(() => {
          type$a([RenderQueueDesc])(GbufferStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'type', 'renderQueues');
        apply(() => {
          ccclass$H('GbufferStage')(GbufferStage);
        }, 'ccclass', null);
      }
      function patch_LightingStage(ctx, apply = defaultExec) {
        const {
          LightingStage,
          Material,
          RenderQueueDesc
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(LightingStage.prototype, '_deferredMaterial', () => {
            return null;
          });
        }, 'displayOrder', '_deferredMaterial');
        apply(() => {
          serializable$l(LightingStage.prototype, '_deferredMaterial', () => {
            return null;
          });
        }, 'serializable', '_deferredMaterial');
        apply(() => {
          type$a(Material)(LightingStage.prototype, '_deferredMaterial', () => {
            return null;
          });
        }, 'type', '_deferredMaterial');
        apply(() => {
          displayOrder$2()(LightingStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'displayOrder', 'renderQueues');
        apply(() => {
          serializable$l(LightingStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'serializable', 'renderQueues');
        apply(() => {
          type$a([RenderQueueDesc])(LightingStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'type', 'renderQueues');
        apply(() => {
          ccclass$H('LightingStage')(LightingStage);
        }, 'ccclass', null);
      }
      function patch_MainFlow(ctx, apply = defaultExec) {
        const {
          MainFlow
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('MainFlow')(MainFlow);
        }, 'ccclass', null);
      }
      function patch_PostProcessStage(ctx, apply = defaultExec) {
        const {
          PostProcessStage,
          Material,
          RenderQueueDesc
        } = {
          ...ctx
        };
        apply(() => {
          displayOrder$2()(PostProcessStage.prototype, '_postProcessMaterial', () => {
            return null;
          });
        }, 'displayOrder', '_postProcessMaterial');
        apply(() => {
          serializable$l(PostProcessStage.prototype, '_postProcessMaterial', () => {
            return null;
          });
        }, 'serializable', '_postProcessMaterial');
        apply(() => {
          type$a(Material)(PostProcessStage.prototype, '_postProcessMaterial', () => {
            return null;
          });
        }, 'type', '_postProcessMaterial');
        apply(() => {
          displayOrder$2()(PostProcessStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'displayOrder', 'renderQueues');
        apply(() => {
          serializable$l(PostProcessStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'serializable', 'renderQueues');
        apply(() => {
          type$a([RenderQueueDesc])(PostProcessStage.prototype, 'renderQueues', () => {
            return [];
          });
        }, 'type', 'renderQueues');
        apply(() => {
          ccclass$H('PostProcessStage')(PostProcessStage);
        }, 'ccclass', null);
      }
      function patch_ReflectionProbeFlow(ctx, apply = defaultExec) {
        const {
          ReflectionProbeFlow
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('ReflectionProbeFlow')(ReflectionProbeFlow);
        }, 'ccclass', null);
      }
      function patch_ReflectionProbeStage(ctx, apply = defaultExec) {
        const {
          ReflectionProbeStage
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('ReflectionProbeStage')(ReflectionProbeStage);
        }, 'ccclass', null);
      }
      function patch_RenderFlow(ctx, apply = defaultExec) {
        const {
          RenderFlow,
          RenderStage
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(RenderFlow.prototype, '_name', () => {
            return '';
          });
        }, 'serializable', '_name');
        apply(() => {
          displayOrder$2()(RenderFlow.prototype, '_name', () => {
            return '';
          });
        }, 'displayOrder', '_name');
        apply(() => {
          serializable$l(RenderFlow.prototype, '_priority', () => {
            return 0;
          });
        }, 'serializable', '_priority');
        apply(() => {
          displayOrder$2()(RenderFlow.prototype, '_priority', () => {
            return 0;
          });
        }, 'displayOrder', '_priority');
        apply(() => {
          serializable$l(RenderFlow.prototype, '_tag', () => {
            return 0;
          });
        }, 'serializable', '_tag');
        apply(() => {
          displayOrder$2()(RenderFlow.prototype, '_tag', () => {
            return 0;
          });
        }, 'displayOrder', '_tag');
        apply(() => {
          serializable$l(RenderFlow.prototype, '_stages', () => {
            return [];
          });
        }, 'serializable', '_stages');
        apply(() => {
          type$a([RenderStage])(RenderFlow.prototype, '_stages', () => {
            return [];
          });
        }, 'type', '_stages');
        apply(() => {
          displayOrder$2()(RenderFlow.prototype, '_stages', () => {
            return [];
          });
        }, 'displayOrder', '_stages');
        apply(() => {
          ccclass$H('RenderFlow')(RenderFlow);
        }, 'ccclass', null);
      }
      function patch_RenderQueueDesc(ctx, apply = defaultExec) {
        const {
          RenderQueueDesc,
          RenderQueueSortMode,
          CCString
        } = {
          ...ctx
        };
        apply(() => {
          editable$5(RenderQueueDesc.prototype);
        }, 'editable', 'isTransparent');
        apply(() => {
          serializable$l(RenderQueueDesc.prototype, 'isTransparent', () => {
            return false;
          });
        }, 'serializable', 'isTransparent');
        apply(() => {
          type$a(RenderQueueSortMode)(RenderQueueDesc.prototype, 'sortMode', () => {
            return 0;
          });
        }, 'type', 'sortMode');
        apply(() => {
          type$a([CCString])(RenderQueueDesc.prototype, 'stages', () => {
            return [];
          });
        }, 'type', 'stages');
        apply(() => {
          ccclass$H('RenderQueueDesc')(RenderQueueDesc);
        }, 'ccclass', null);
      }
      function patch_RenderStage(ctx, apply = defaultExec) {
        const {
          RenderStage
        } = {
          ...ctx
        };
        apply(() => {
          serializable$l(RenderStage.prototype, '_name', () => {
            return '';
          });
        }, 'serializable', '_name');
        apply(() => {
          displayOrder$2()(RenderStage.prototype, '_name', () => {
            return '';
          });
        }, 'displayOrder', '_name');
        apply(() => {
          serializable$l(RenderStage.prototype, '_priority', () => {
            return 0;
          });
        }, 'serializable', '_priority');
        apply(() => {
          displayOrder$2()(RenderStage.prototype, '_priority', () => {
            return 0;
          });
        }, 'displayOrder', '_priority');
        apply(() => {
          serializable$l(RenderStage.prototype, '_tag', () => {
            return 0;
          });
        }, 'serializable', '_tag');
        apply(() => {
          displayOrder$2()(RenderStage.prototype, '_tag', () => {
            return 0;
          });
        }, 'displayOrder', '_tag');
        apply(() => {
          ccclass$H('RenderStage')(RenderStage);
        }, 'ccclass', null);
      }
      function patch_ShadowFlow(ctx, apply = defaultExec) {
        const {
          ShadowFlow
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('ShadowFlow')(ShadowFlow);
        }, 'ccclass', null);
      }
      function patch_ShadowStage(ctx, apply = defaultExec) {
        const {
          ShadowStage
        } = {
          ...ctx
        };
        apply(() => {
          ccclass$H('ShadowStage')(ShadowStage);
        }, 'ccclass', null);
      }

      applyMixins(jsb.Asset, [CallbacksInvoker, ExtraEventMethods]);
      const assetProto = jsb.Asset.prototype;
      assetProto._ctor = function () {
        this.loaded = true;
        this._ref = 0;
        this.__nativeRefs = {};
        this.__jsb_ref_id = undefined;
        this._iN$t = null;
        this.__editorExtras__ = {
          editorOnly: true
        };
        this._callbackTable = createMap(true);
        this._file = null;
      };
      Object.defineProperty(assetProto, '_nativeAsset', {
        get() {
          return this._file;
        },
        set(obj) {
          this._file = obj;
        }
      });
      Object.defineProperty(assetProto, 'nativeUrl', {
        get() {
          if (!this._nativeUrl) {
            if (!this._native) return '';
            const 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;
        }
      });
      Object.defineProperty(assetProto, 'refCount', {
        configurable: true,
        enumerable: true,
        get() {
          return this._ref;
        }
      });
      assetProto.addRef = function () {
        this._ref++;
        this.addAssetRef();
        return this;
      };
      assetProto.decRef = function (autoRelease = true) {
        this.decAssetRef();
        if (this._ref > 0) {
          this._ref--;
        }
        if (autoRelease) {
          cclegacy.assetManager.getReleaseManager().tryRelease(this);
        }
        return this;
      };
      assetProto.toString = function () {
        return this.nativeUrl;
      };
      assetProto.createNode = null;
      const Asset = exports("Asset", jsb.Asset);
      cclegacy.Asset = jsb.Asset;
      patch_cc_Asset({
        Asset
      });

      const ImageAsset$1 = exports("ImageAsset", jsb.ImageAsset);
      const jsbWindow$1 = jsb.window;
      const extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc'];
      function isImageBitmap(imageSource) {
        return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap);
      }
      function isNativeImage(imageSource) {
        if (imageSource._compressed === true) {
          return false;
        }
        return imageSource instanceof jsbWindow$1.HTMLImageElement || imageSource instanceof jsbWindow$1.HTMLCanvasElement || isImageBitmap(imageSource);
      }
      const imageAssetProto = ImageAsset$1.prototype;
      imageAssetProto._ctor = function (nativeAsset) {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        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);
        }
      };
      Object.defineProperty(imageAssetProto, '_nativeAsset', {
        configurable: true,
        enumerable: true,
        get() {
          return this._nativeData;
        },
        set(value) {
          if (!(value instanceof jsbWindow$1.HTMLElement) && !isImageBitmap(value)) {
            value.format = value.format || this.format;
          }
          this.reset(value);
        }
      });
      Object.defineProperty(imageAssetProto, 'data', {
        configurable: true,
        enumerable: true,
        get() {
          if (this._nativeData && isNativeImage(this._nativeData)) {
            return this._nativeData;
          }
          return this._nativeData && this._nativeData._data;
        }
      });
      imageAssetProto._setRawAsset = function (filename, inLibrary = true) {
        if (inLibrary !== false) {
          this._native = filename || '';
        } else {
          this._native = `/${filename}`;
        }
      };
      imageAssetProto.reset = function (data) {
        this._nativeData = data;
        if (!(data instanceof jsbWindow$1.HTMLElement)) {
          if (data.format !== undefined) {
            this.format = data.format;
          }
        }
        this._syncDataToNative();
      };
      const superDestroy = jsb.Asset.prototype.destroy;
      imageAssetProto.destroy = function () {
        if (this.data && this.data instanceof jsbWindow$1.HTMLImageElement) {
          this.data.src = '';
          this._setRawAsset('');
          this.data.destroy();
        } else if (isImageBitmap(this.data)) {
          this.data.close && this.data.close();
        }
        return superDestroy.call(this);
      };
      Object.defineProperty(imageAssetProto, 'width', {
        configurable: true,
        enumerable: true,
        get() {
          return this._nativeData.width || this._width;
        }
      });
      Object.defineProperty(imageAssetProto, 'height', {
        configurable: true,
        enumerable: true,
        get() {
          return this._nativeData.height || this._height;
        }
      });
      imageAssetProto._syncDataToNative = function () {
        const data = this._nativeData;
        this._width = data.width;
        this._height = data.height;
        this.setWidth(this._width);
        this.setHeight(this._height);
        this.url = this.nativeUrl;
        if (data instanceof jsbWindow$1.HTMLCanvasElement) {
          this.setData(data._data.data);
        } else if (data instanceof jsbWindow$1.HTMLImageElement) {
          this.setData(data._data);
          if (data._mipmapLevelDataSize) {
            this.setMipmapLevelDataSize(data._mipmapLevelDataSize);
          }
        } else {
          if (!this._nativeData._data) {
            console.error(`[ImageAsset] setData bad argument ${this._nativeData}`);
            return;
          }
          this.setData(this._nativeData._data);
          if (this._nativeData.mipmapLevelDataSize) {
            this.setMipmapLevelDataSize(this._nativeData.mipmapLevelDataSize);
          }
        }
      };
      imageAssetProto._serialize = function () {
      };
      imageAssetProto._deserialize = function (data) {
        let fmtStr = '';
        if (typeof data === 'string') {
          fmtStr = data;
        } else {
          this._width = data.w;
          this._height = data.h;
          fmtStr = data.fmt;
        }
        const device = deviceManager.gfxDevice;
        const extensionIDs = fmtStr.split('_');
        let preferedExtensionIndex = Number.MAX_VALUE;
        let format = this.format;
        let ext = '';
        const SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS;
        for (const extensionID of extensionIDs) {
          const extFormat = extensionID.split('@');
          const i = parseInt(extFormat[0], undefined);
          const tmpExt = extnames[i] || extFormat[0];
          const index = SupportTextureFormats.indexOf(tmpExt);
          if (index !== -1 && index < preferedExtensionIndex) {
            const fmt = extFormat[1] ? parseInt(extFormat[1]) : this.format;
            if (tmpExt === '.astc' && (!device || !(device.getFormatFeatures(89) & 2))) {
              continue;
            } else if (tmpExt === '.pvr' && (!device || !(device.getFormatFeatures(86) & 2))) {
              continue;
            } else if ((fmt === 72 || fmt === 1026) && (!device || !(device.getFormatFeatures(72) & 2))) {
              continue;
            } else if ((fmt === 73 || fmt === 77) && (!device || !(device.getFormatFeatures(73) & 2))) {
              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);
        }
      };
      cclegacy.ImageAsset = jsb.ImageAsset;
      patch_cc_ImageAsset({
        ImageAsset: ImageAsset$1
      });

      const PixelFormat = {
        "RGB565": 47,
        "RGB5A1": 49,
        "RGBA4444": 50,
        "RGB888": 24,
        "RGB32F": 32,
        "RGBA8888": 35,
        "BGRA8888": 36,
        "RGBA32F": 44,
        "A8": 1,
        "I8": 2,
        "AI8": 3,
        "RGB_PVRTC_2BPPV1": 83,
        "RGBA_PVRTC_2BPPV1": 84,
        "RGB_A_PVRTC_2BPPV1": 1024,
        "RGB_PVRTC_4BPPV1": 85,
        "RGBA_PVRTC_4BPPV1": 86,
        "RGB_A_PVRTC_4BPPV1": 1025,
        "RGB_ETC1": 72,
        "RGBA_ETC1": 1026,
        "RGB_ETC2": 73,
        "RGBA_ETC2": 77,
        "RGBA_ASTC_4x4": 89,
        "RGBA_ASTC_5x4": 90,
        "RGBA_ASTC_5x5": 91,
        "RGBA_ASTC_6x5": 92,
        "RGBA_ASTC_6x6": 93,
        "RGBA_ASTC_8x5": 94,
        "RGBA_ASTC_8x6": 95,
        "RGBA_ASTC_8x8": 96,
        "RGBA_ASTC_10x5": 97,
        "RGBA_ASTC_10x6": 98,
        "RGBA_ASTC_10x8": 99,
        "RGBA_ASTC_10x10": 100,
        "RGBA_ASTC_12x10": 101,
        "RGBA_ASTC_12x12": 102
      };
      const WrapMode$1 = {
        "REPEAT": 0,
        "CLAMP_TO_EDGE": 2,
        "MIRRORED_REPEAT": 1,
        "CLAMP_TO_BORDER": 3
      };
      const TextureFilter = {
        "NONE": 0,
        "LINEAR": 2,
        "NEAREST": 1
      };

      var _dec$2n, _class$2n, _dec2$1B, _class2$1$, _dec3$17, _class3$E;
      let Script = exports("Script", (_dec$2n = ccclass$H('cc.Script'), _dec$2n(_class$2n = class Script extends Asset {}) || _class$2n));
      cclegacy._Script = Script;
      let JavaScript = exports("JavaScript", (_dec2$1B = ccclass$H('cc.JavaScript'), _dec2$1B(_class2$1$ = class JavaScript extends Script {}) || _class2$1$));
      cclegacy._JavaScript = JavaScript;
      let TypeScript = exports("TypeScript", (_dec3$17 = ccclass$H('cc.TypeScript'), _dec3$17(_class3$E = class TypeScript extends Script {}) || _class3$E));
      cclegacy._TypeScript = TypeScript;

      var _dec$2m, _class$2m, _class2$1_, _initializer$1S, _initializer2$1p, _initializer3$11, _initializer4$U, _initializer5$G;
      let EventHandler = exports("EventHandler", (_dec$2m = ccclass$H('cc.ClickEvent'), _dec$2m(_class$2m = (_class2$1_ = class EventHandler {
        constructor() {
          this.target = _initializer$1S && _initializer$1S();
          this.component = _initializer2$1p && _initializer2$1p();
          this._componentId = _initializer3$11 && _initializer3$11();
          this.handler = _initializer4$U && _initializer4$U();
          this.customEventData = _initializer5$G && _initializer5$G();
        }
        get _componentName() {
          this._genCompIdIfNeeded();
          return this._compId2Name(this._componentId);
        }
        set _componentName(value) {
          this._componentId = this._compName2Id(value);
        }
        static emitEvents(events, ...args) {
          for (let i = 0, l = events.length; i < l; i++) {
            const event = events[i];
            if (!(event instanceof EventHandler)) {
              continue;
            }
            event.emit(args);
          }
        }
        emit(params) {
          const target = this.target;
          if (!legacyCC.isValid(target)) {
            return;
          }
          this._genCompIdIfNeeded();
          const compType = legacyCC.js.getClassById(this._componentId);
          const comp = target.getComponent(compType);
          if (!legacyCC.isValid(comp)) {
            return;
          }
          const 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);
        }
        _compName2Id(compName) {
          const comp = legacyCC.js.getClassByName(compName);
          return legacyCC.js.getClassId(comp);
        }
        _compId2Name(compId) {
          const comp = legacyCC.js.getClassById(compId);
          return legacyCC.js.getClassName(comp);
        }
        _genCompIdIfNeeded() {
          if (!this._componentId) {
            this._componentName = this.component;
            this.component = '';
          }
        }
      }, (_initializer$1S = applyDecoratedInitializer(_class2$1_.prototype, "target", [serializable$l], function () {
        return null;
      }), _initializer2$1p = applyDecoratedInitializer(_class2$1_.prototype, "component", [serializable$l], function () {
        return '';
      }), _initializer3$11 = applyDecoratedInitializer(_class2$1_.prototype, "_componentId", [serializable$l], function () {
        return '';
      }), _initializer4$U = applyDecoratedInitializer(_class2$1_.prototype, "handler", [serializable$l], function () {
        return '';
      }), _initializer5$G = applyDecoratedInitializer(_class2$1_.prototype, "customEventData", [serializable$l], function () {
        return '';
      })), _class2$1_)) || _class$2m));

      var _dec$2l, _dec2$1A, _class$2l, _class2$1Z, _initializer$1R, _initializer2$1o, _initializer3$10, _class3$D;
      const idGenerator = new IDGenerator('Comp');
      const IsOnLoadCalled$1 = CCObject.Flags.IsOnLoadCalled;
      const NullNode = null;
      let Component = exports("Component", (_dec$2l = ccclass$H('cc.Component'), _dec2$1A = type$a(Script), _dec$2l(_class$2l = (_class2$1Z = (_class3$D = class Component extends CCObject {
        constructor() {
          super();
          this.node = _initializer$1R && _initializer$1R();
          this._enabled = _initializer2$1o && _initializer2$1o();
          this.__prefab = _initializer3$10 && _initializer3$10();
          this._sceneGetter = null;
          this._id = idGenerator.getNewId();
        }
        get name() {
          if (this._name) {
            return this._name;
          }
          let className = getClassName(this);
          const trimLeft = className.lastIndexOf('.');
          if (trimLeft >= 0) {
            className = className.slice(trimLeft + 1);
          }
          if (this.node) {
            return `${this.node.name}<${className}>`;
          } else {
            return className;
          }
        }
        set name(value) {
          this._name = value;
        }
        get uuid() {
          return this._id;
        }
        get __scriptAsset() {
          return null;
        }
        get enabled() {
          return this._enabled;
        }
        set enabled(value) {
          if (this._enabled !== value) {
            this._enabled = value;
            if (this.node.activeInHierarchy) {
              const compScheduler = legacyCC.director._compScheduler;
              if (value) {
                compScheduler.enableComp(this);
              } else {
                compScheduler.disableComp(this);
              }
            }
          }
        }
        get enabledInHierarchy() {
          return this._enabled && this.node && this.node.activeInHierarchy;
        }
        get _isOnLoadCalled() {
          return this._objFlags & IsOnLoadCalled$1;
        }
        _getRenderScene() {
          if (this._sceneGetter) {
            return this._sceneGetter();
          }
          return this.node.scene.renderScene;
        }
        addComponent(typeOrClassName) {
          return this.node.addComponent(typeOrClassName);
        }
        getComponent(typeOrClassName) {
          return this.node.getComponent(typeOrClassName);
        }
        getComponents(typeOrClassName) {
          return this.node.getComponents(typeOrClassName);
        }
        getComponentInChildren(typeOrClassName) {
          return this.node.getComponentInChildren(typeOrClassName);
        }
        getComponentsInChildren(typeOrClassName) {
          return this.node.getComponentsInChildren(typeOrClassName);
        }
        destroy() {
          if (super.destroy()) {
            if (this._enabled && this.node.activeInHierarchy) {
              legacyCC.director._compScheduler.disableComp(this);
            }
            return true;
          }
          return false;
        }
        _onPreDestroy() {
          this.unscheduleAllCallbacks();
          legacyCC.director._nodeActivator.destroyComp(this);
          this.node._removeComponent(this);
        }
        _instantiate(cloned) {
          if (!cloned) {
            cloned = legacyCC.instantiate._clone(this, this);
          }
          if (cloned) {
            cloned.node = NullNode;
          }
          return cloned;
        }
        schedule(callback, interval = 0, repeat = legacyCC.macro.REPEAT_FOREVER, 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;
          const scheduler = legacyCC.director.getScheduler();
          const paused = scheduler.isTargetPaused(this);
          scheduler.schedule(callback, this, interval, repeat, delay, paused);
        }
        scheduleOnce(callback, delay = 0) {
          this.schedule(callback, 0, 0, delay);
        }
        unschedule(callback_fn) {
          if (!callback_fn) {
            return;
          }
          legacyCC.director.getScheduler().unschedule(callback_fn, this);
        }
        unscheduleAllCallbacks() {
          legacyCC.director.getScheduler().unscheduleAllForTarget(this);
        }
        get internalUpdate() {
          return this.update;
        }
        get internalLateUpdate() {
          return this.lateUpdate;
        }
        get internalPreload() {
          return this.__preload;
        }
        get internalOnLoad() {
          return this.onLoad;
        }
        get internalStart() {
          return this.start;
        }
        get internalOnEnable() {
          return this.onEnable;
        }
        get internalOnDisable() {
          return this.onDisable;
        }
        get internalOnDestroy() {
          return this.onDestroy;
        }
      }, _class3$D.EventHandler = EventHandler, _class3$D._executionOrder = 0, _class3$D._requireComponent = null, _class3$D.system = null, _class3$D), (_applyDecoratedDescriptor(_class2$1Z.prototype, "__scriptAsset", [_dec2$1A], Object.getOwnPropertyDescriptor(_class2$1Z.prototype, "__scriptAsset"), _class2$1Z.prototype), _initializer$1R = applyDecoratedInitializer(_class2$1Z.prototype, "node", [serializable$l], function () {
        return NullNode;
      }), _initializer2$1o = applyDecoratedInitializer(_class2$1Z.prototype, "_enabled", [serializable$l], function () {
        return true;
      }), _initializer3$10 = applyDecoratedInitializer(_class2$1Z.prototype, "__prefab", [serializable$l], function () {
        return null;
      })), _class2$1Z)) || _class$2l));
      value(Component, '_registerEditorProps', (cls, props) => {
        let reqComp = props.requireComponent;
        if (reqComp) {
          if (Array.isArray(reqComp)) {
            reqComp = reqComp.filter(Boolean);
          }
          cls._requireComponent = reqComp;
        }
        const order = props.executionOrder;
        if (order && typeof order === 'number') {
          cls._executionOrder = order;
        }
      });
      legacyCC.Component = Component;

      var _dec$2k, _class$2k, _class2$1Y, _initializer$1Q;
      let MissingScript = exports("MissingScript", (_dec$2k = ccclass$H('cc.MissingScript'), _dec$2k(_class$2k = (_class2$1Y = class MissingScript extends Component {
        static safeFindClass(id) {
          const cls = getClassById(id);
          if (cls) {
            return cls;
          }
          cclegacy.deserialize.reportMissingClass(id);
          return undefined;
        }
        constructor() {
          super();
          this._$erialized = _initializer$1Q && _initializer$1Q();
        }
        onLoad() {
          warnID(4600, this.node.name);
        }
      }, (_initializer$1Q = applyDecoratedInitializer(_class2$1Y.prototype, "_$erialized", [serializable$l, editorOnly], function () {
        return null;
      })), _class2$1Y)) || _class$2k));
      cclegacy._MissingScript = MissingScript;
      try {
        const props = MissingScript.__values__;
        if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
          errorID(16338);
          errorID(16339, props.join(', '));
        }
      } catch (e) {
        errorID(16340, `${e}`);
      }

      const VERSION = 1;
      const MAGIC = 0x4E4F4343;
      const CHUNK_ALIGN_AS = 8;
      class CCON {
        constructor(document, chunks) {
          this._document = document;
          this._chunks = chunks;
        }
        get document() {
          return this._document;
        }
        get chunks() {
          return this._chunks;
        }
      }
      function parseCCONJson(json) {
        const cconPreface = json;
        return {
          chunks: cconPreface.chunks,
          document: cconPreface.document
        };
      }
      function decodeCCONBinary(bytes) {
        if (bytes.length < 16) {
          throw new InvalidCCONError(getError(13102));
        }
        const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
        const magic = dataView.getUint32(0, true);
        if (magic !== MAGIC) {
          throw new InvalidCCONError(getError(13100));
        }
        const version = dataView.getUint32(4, true);
        if (version !== VERSION) {
          throw new InvalidCCONError(getError(13101, version));
        }
        const dataByteLength = dataView.getUint32(8, true);
        if (dataByteLength !== dataView.byteLength) {
          throw new InvalidCCONError(getError(13102));
        }
        let chunksStart = 12;
        const jsonDataLength = dataView.getUint32(chunksStart, true);
        chunksStart += 4;
        const jsonData = new Uint8Array(dataView.buffer, chunksStart + dataView.byteOffset, jsonDataLength);
        chunksStart += jsonDataLength;
        const jsonString = decodeJson(jsonData);
        let json;
        try {
          json = JSON.parse(jsonString);
        } catch (err) {
          throw new InvalidCCONError(err);
        }
        const chunks = [];
        while (chunksStart < dataView.byteLength) {
          if (chunksStart % CHUNK_ALIGN_AS !== 0) {
            const padding = CHUNK_ALIGN_AS - chunksStart % CHUNK_ALIGN_AS;
            chunksStart += padding;
          }
          const 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) {
          const {
            Buffer
          } = globalThis;
          return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString();
        } else {
          throw new Error(getError(13104));
        }
      }
      class InvalidCCONError extends Error {}
      cclegacy.internal.parseCCONJson = parseCCONJson;
      cclegacy.internal.decodeCCONBinary = decodeCCONBinary;
      cclegacy.internal.CCON = CCON;

      function compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) {
        if (defaultValue instanceof cclegacy.ValueType) {
          if (!assumeHavePropIfIsValue) {
            sources.push('if(prop){');
          }
          const ctorCode = getClassName(defaultValue);
          sources.push(`s._deserializeFastDefinedObject(o${accessorToSet},prop,${ctorCode});`);
          if (!assumeHavePropIfIsValue) {
            sources.push(`}else o${accessorToSet}=null;`);
          }
        } else {
          sources.push(`
if (prop) {
    s._deserializeAndAssignField(o, prop, ${propNameLiteralToSet});
} else {
    o${accessorToSet}=null;
}
`);
        }
      }
      const compileDeserialize = compileDeserializeJIT ;
      const DELIMITER = CCClass.Attr.DELIMETER;
      const POSTFIX_TYPE = `${DELIMITER}type`;
      const POSTFIX_DEFAULT = `${DELIMITER}default`;
      const POSTFIX_FORMERLY_SERIALIZED_AS = `${DELIMITER}formerlySerializedAs`;
      function compileDeserializeJIT(self, klass) {
        const attrs = CCClass.Attr.getClassAttrs(klass);
        const props = klass.__values__;
        const sources = ['var prop;'];
        const fastMode = canBeDeserializedInFastMode(klass);
        for (let p = 0; p < props.length; p++) {
          const propName = props[p];
          let accessorToSet;
          let propNameLiteralToSet;
          if (CCClass.IDENTIFIER_RE.test(propName)) {
            propNameLiteralToSet = `"${propName}"`;
            accessorToSet = `.${propName}`;
          } else {
            propNameLiteralToSet = CCClass.escapeForJS(propName);
            accessorToSet = `[${propNameLiteralToSet}]`;
          }
          let accessorToGet = accessorToSet;
          if (attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS]) {
            const 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"){`);
          const defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
          const userType = attrs[propName + POSTFIX_TYPE];
          if (fastMode && (defaultValue !== undefined || userType)) {
            const 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, cclegacy.Node) || isChildClassOf(klass, cclegacy.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 {
          const defaultType = typeof defaultValue;
          return defaultType === 'string' || defaultType === 'number' || defaultType === 'boolean';
        }
      }
      class DeserializerPool extends Pool$1 {
        constructor() {
          super(deserializer => {
            deserializer.clear();
          }, 1);
        }
      }
      DeserializerPool.prototype.get = function (details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
        const cache = this._get();
        if (cache) {
          cache.reset(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
          return cache;
        } else {
          return new _Deserializer(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        }
      };
      class _Deserializer {
        get ignoreEditorOnly() {
          return this._ignoreEditorOnly;
        }
        constructor(result, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
          this.deserializedList = [];
          this.deserializedData = null;
          this.result = result;
          this.customEnv = customEnv;
          this._classFinder = classFinder;
          this._reportMissingClass = reportMissingClass;
          this._onDereferenced = classFinder === null || classFinder === void 0 ? void 0 : classFinder.onDereferenced;
        }
        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;
        }
        clear() {
          this.result = null;
          this.customEnv = null;
          this.deserializedList.length = 0;
          this.deserializedData = null;
          this._classFinder = null;
          this._reportMissingClass = null;
          this._onDereferenced = null;
        }
        deserialize(serializedData) {
          let fromCCON = false;
          let 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
          };
          const 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;
        }
        _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);
              }
          }
        }
        _deserializeTypedArrayView(value) {
          return globalThis[value.ctor].from(value.array);
        }
        _deserializeTypedArrayViewRef(value) {
          const {
            offset,
            length,
            ctor: constructorName
          } = value;
          const obj = new globalThis[constructorName](this._mainBinChunk.buffer, this._mainBinChunk.byteOffset + offset, length);
          return obj;
        }
        _deserializeArray(value) {
          const obj = new Array(value.length);
          let prop;
          for (let i = 0; i < value.length; i++) {
            prop = value[i];
            if (typeof prop === 'object' && prop) {
              const isAssetType = this._deserializeAndAssignField(obj, prop, `${i}`);
              if (isAssetType) {
                obj[i] = null;
              }
            } else {
              obj[i] = prop;
            }
          }
          return obj;
        }
        _deserializePlainObject(value) {
          const obj = {};
          this._fillPlainObject(obj, value);
          return obj;
        }
        _deserializeTypeTaggedObject(value, globalIndex, owner, propName) {
          const type = value.__type__;
          const klass = this._classFinder(type, value, owner, propName);
          if (!klass) {
            const notReported = this._classFinder === getClassById;
            if (notReported) {
              this._reportMissingClass(type);
            }
            return null;
          }
          const createObject = constructor => {
            const obj = new constructor();
            if (globalIndex >= 0) {
              this.deserializedList[globalIndex] = obj;
            }
            return obj;
          };
          {
            const obj = createObject(klass);
            this._deserializeInto(value, obj, klass);
            return obj;
          }
        }
        _deserializeInto(value, object, constructor, skipCustomized = false) {
          if (!skipCustomized && object[deserializeTag]) {
            this._runCustomizedDeserialize(value, object, constructor);
            return;
          }
          if (object._deserialize) {
            object._deserialize(value.content, this);
            return;
          }
          if (cclegacy.Class._isCCClass(constructor)) {
            this._deserializeFireClass(object, value, constructor);
          } else {
            this._deserializeFastDefinedObject(object, value, constructor);
          }
        }
        _runCustomizedDeserialize(value, object, constructor) {
          const serializationInput = {
            readProperty: name => {
              const serializedField = value[name];
              if (typeof serializedField !== 'object' || !serializedField) {
                return serializedField;
              } else {
                return this._deserializeObjectField(serializedField);
              }
            },
            readThis: () => {
              this._deserializeInto(value, object, constructor, true);
            },
            readSuper: () => {
              const superConstructor = getSuper(constructor);
              if (superConstructor) {
                this._deserializeInto(value, object, superConstructor);
              }
            }
          };
          object[deserializeTag](serializationInput, this._context);
        }
        _deserializeFireClass(obj, serialized, klass) {
          let deserialize;
          if (klass.hasOwnProperty('__deserialize__')) {
            deserialize = klass.__deserialize__;
          } else {
            deserialize = compileDeserialize(this, klass);
            try {
              if (klass === MissingScript) {
                const props = klass.__values__;
                if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
                  errorID(16341);
                  errorID(16342, props.join(', '));
                }
                const rawDeserialize = deserialize;
                deserialize = function (deserializer, object, deserialized, constructor) {
                  rawDeserialize(deserializer, object, deserialized, constructor);
                  if (!object._$erialized) {
                    errorID(16343, JSON.stringify(deserialized));
                  }
                };
              }
            } catch (e) {
              errorID(16344, `${e}`);
            }
            value(klass, '__deserialize__', deserialize, true);
          }
          deserialize(this, obj, serialized, klass);
        }
        _deserializeAndAssignField(obj, serializedField, propName) {
          const id = serializedField.__id__;
          if (typeof id === 'number') {
            const field = this.deserializedList[id];
            if (field) {
              obj[propName] = field;
            } else {
              var _this$_onDereferenced;
              const 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 {
            const uuid = serializedField.__uuid__;
            if (uuid) {
              const expectedType = serializedField.__expectedType__;
              this.result.push(obj, propName, uuid, expectedType);
            } else {
              obj[propName] = this._deserializeObject(serializedField, -1);
            }
          }
          return false;
        }
        _deserializeObjectField(serializedField) {
          const id = serializedField.__id__;
          if (typeof id === 'number') {
            const field = this.deserializedList[id];
            if (field) {
              return field;
            } else {
              const source = this._serializedData[id];
              const field = this._deserializeObject(source, id, undefined, undefined);
              return field;
            }
          } else {
            const 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);
            }
          }
        }
        _fillPlainObject(instance, serialized) {
          for (const propName in serialized) {
            if (!serialized.hasOwnProperty(propName)) {
              continue;
            }
            const prop = serialized[propName];
            if (typeof prop !== 'object') {
              if (propName !== '__type__') {
                instance[propName] = prop;
              }
            } else if (prop) {
              const isAssetType = this._deserializeAndAssignField(instance, prop, propName);
              if (isAssetType) {
                instance[propName] = null;
              }
            } else {
              instance[propName] = null;
            }
          }
        }
        _deserializeFastDefinedObject(instance, serialized, klass) {
          if (klass === cclegacy.Vec2) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            return;
          } else if (klass === cclegacy.Vec3) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            instance.z = serialized.z || 0;
            return;
          } else if (klass === cclegacy.Color) {
            instance.r = serialized.r || 0;
            instance.g = serialized.g || 0;
            instance.b = serialized.b || 0;
            const a = serialized.a;
            instance.a = a === undefined ? 255 : a;
            return;
          } else if (klass === cclegacy.Size) {
            instance.width = serialized.width || 0;
            instance.height = serialized.height || 0;
            return;
          }
          const attrs = CCClass.Attr.getClassAttrs(klass);
          const 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 (let i = 0; i < props.length; i++) {
            const propName = props[i];
            let value = serialized[propName];
            const 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;
            }
          }
        }
      }
      _Deserializer.pool = new DeserializerPool();
      function deserializeDynamic(data, details, options) {
        var _options$reportMissin;
        options = options || {};
        const classFinder = options.classFinder || getClassById;
        const createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE;
        const customEnv = options.customEnv;
        const ignoreEditorOnly = options.ignoreEditorOnly;
        const reportMissingClass = (_options$reportMissin = options.reportMissingClass) !== null && _options$reportMissin !== void 0 ? _options$reportMissin : cclegacy.deserialize.reportMissingClass;
        details.init();
        const deserializer = _Deserializer.pool.get(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        cclegacy.game._isCloning = true;
        const res = deserializer.deserialize(data);
        cclegacy.game._isCloning = false;
        _Deserializer.pool.put(deserializer);
        if (createAssetRefs) {
          details.assignAssetsBy((uuid, options) => EditorExtends.serialize.asAsset(uuid, options.type));
        }
        return res;
      }

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

      const 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];
      }
      const setterMap = [(obj, data) => {
        obj.x = data[1];
        obj.y = data[2];
      }, (obj, data) => {
        obj.x = data[1];
        obj.y = data[2];
        obj.z = data[3];
      }, vec4LikeSetter, vec4LikeSetter, (obj, data) => {
        Color$1.fromUint32(obj, data[1]);
      }, (obj, data) => {
        obj.width = data[1];
        obj.height = data[2];
      }, (obj, data) => {
        obj.x = data[1];
        obj.y = data[2];
        obj.width = data[3];
        obj.height = data[4];
      }, (obj, data) => {
        Mat4.fromArray(obj, data, 1);
      }];
      function deserializeBuiltinValueType(data, owner, key, value) {
        const typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        const object = new constructorMap[typeIndex]();
        const setter = setterMap[typeIndex];
        setter(object, value);
        owner[key] = object;
      }
      function deserializeBuiltinValueTypeInto(data, owner, key, value) {
        const typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        {
          const tmp = owner[key];
          const setter = setterMap[typeIndex];
          setter(tmp, value);
          owner[key] = tmp;
        }
      }

      const SUPPORT_MIN_FORMAT_VERSION = 1;
      const EMPTY_PLACEHOLDER = 0;
      const CLASS_TYPE = 0;
      const CLASS_KEYS = 1;
      const CLASS_PROP_TYPE_OFFSET = 2;
      const MASK_CLASS = 0;
      const OBJ_DATA_MASK = 0;
      const CUSTOM_OBJ_DATA_CLASS = 0;
      const CUSTOM_OBJ_DATA_CONTENT = 1;
      const DICT_JSON_LAYOUT = 0;
      const ARRAY_ITEM_VALUES = 0;
      const PACKED_SECTIONS = 5;
      class Details {
        constructor() {
          this.uuidObjList = null;
          this.uuidPropList = null;
          this.uuidList = null;
          this.uuidTypeList = [];
        }
        init(data) {
          if (data) {
            this.uuidObjList = data[8];
            this.uuidPropList = data[9];
            this.uuidList = data[10];
          } else {
            const used = this.uuidList;
            if (!used) {
              this.uuidList = [];
              this.uuidObjList = [];
              this.uuidPropList = [];
              this.uuidTypeList = [];
            }
          }
        }
        reset() {
          {
            const used = this.uuidList;
            if (used) {
              this.uuidList.length = 0;
              this.uuidObjList.length = 0;
              this.uuidPropList.length = 0;
              this.uuidTypeList.length = 0;
            }
          }
        }
        push(obj, propName, uuid, type) {
          this.uuidObjList.push(obj);
          this.uuidPropList.push(propName);
          this.uuidList.push(uuid);
          this.uuidTypeList.push(type || '');
        }
      } exports("Details", Details);
      Details.pool = new Pool$1(obj => {
        obj.reset();
      }, 5);
      Details.pool.get = function () {
        return this._get() || new Details();
      };
      function dereference(refs, instances, strings) {
        const dataLength = refs.length - 1;
        let i = 0;
        const instanceOffset = refs[dataLength] * 3;
        for (; i < instanceOffset; i += 3) {
          const owner = refs[i];
          const target = instances[refs[i + 2]];
          const keyIndex = refs[i + 1];
          if (keyIndex >= 0) {
            owner[strings[keyIndex]] = target;
          } else {
            owner[~keyIndex] = target;
          }
        }
        for (; i < dataLength; i += 3) {
          const owner = instances[refs[i]];
          const target = instances[refs[i + 2]];
          const keyIndex = refs[i + 1];
          if (keyIndex >= 0) {
            owner[strings[keyIndex]] = target;
          } else {
            owner[~keyIndex] = target;
          }
        }
      }
      function deserializeCCObject(data, objectData) {
        const mask = data[4][objectData[OBJ_DATA_MASK]];
        const clazz = mask[MASK_CLASS];
        const ctor = clazz[CLASS_TYPE];
        const obj = new ctor();
        const keys = clazz[CLASS_KEYS];
        const classTypeOffset = clazz[CLASS_PROP_TYPE_OFFSET];
        const maskTypeOffset = mask[mask.length - 1];
        let i = MASK_CLASS + 1;
        for (; i < maskTypeOffset; ++i) {
          const key = keys[mask[i]];
          obj[key] = objectData[i];
        }
        for (; i < objectData.length; ++i) {
          const key = keys[mask[i]];
          const type = clazz[mask[i] + classTypeOffset];
          const op = ASSIGNMENTS[type];
          op(data, obj, key, objectData[i]);
        }
        return obj;
      }
      function deserializeCustomCCObject(data, ctor, value) {
        const obj = new ctor();
        if (obj._deserialize) {
          obj._deserialize(value, data[0]);
        } 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[5][value];
        } else {
          data[7][~value * 3] = owner;
        }
      }
      function genArrayParser(parser) {
        return (data, owner, key, value) => {
          for (let 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[8][value] = owner;
      }
      function parseClass(data, owner, key, value) {
        owner[key] = deserializeCCObject(data, value);
      }
      function parseCustomClass(data, owner, key, value) {
        const ctor = data[3][value[CUSTOM_OBJ_DATA_CLASS]];
        owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]);
      }
      function parseTRS(data, owner, key, value) {
        const typedArray = owner[key];
        typedArray.set(value);
      }
      function parseDict(data, owner, key, value) {
        const dict = value[DICT_JSON_LAYOUT];
        owner[key] = dict;
        for (let i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) {
          const subKey = value[i];
          const subType = value[i + 1];
          const subValue = value[i + 2];
          const op = ASSIGNMENTS[subType];
          op(data, dict, subKey, subValue);
        }
      }
      function parseArray(data, owner, key, value) {
        const array = value[ARRAY_ITEM_VALUES];
        for (let i = 0; i < array.length; ++i) {
          const subValue = array[i];
          const type = value[i + 1];
          if (type !== 0) {
            const op = ASSIGNMENTS[type];
            op(data, array, i, subValue);
          }
        }
        owner[key] = array;
      }
      const ASSIGNMENTS = new Array(13);
      ASSIGNMENTS[0] = assignSimple;
      ASSIGNMENTS[1] = assignInstanceRef;
      ASSIGNMENTS[2] = genArrayParser(assignInstanceRef);
      ASSIGNMENTS[3] = genArrayParser(parseAssetRefByInnerObj);
      ASSIGNMENTS[4] = parseClass;
      ASSIGNMENTS[5] = deserializeBuiltinValueTypeInto;
      ASSIGNMENTS[6] = parseAssetRefByInnerObj;
      ASSIGNMENTS[7] = parseTRS;
      ASSIGNMENTS[8] = deserializeBuiltinValueType;
      ASSIGNMENTS[9] = genArrayParser(parseClass);
      ASSIGNMENTS[10] = parseCustomClass;
      ASSIGNMENTS[11] = parseDict;
      ASSIGNMENTS[12] = parseArray;
      function parseInstances(data) {
        const instances = data[5];
        const instanceTypes = data[6];
        const instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : instanceTypes.length;
        let rootIndex = instances[instances.length - 1];
        let normalObjectCount = instances.length - instanceTypesLen;
        if (typeof rootIndex !== 'number') {
          rootIndex = 0;
        } else {
          if (rootIndex < 0) {
            rootIndex = ~rootIndex;
          }
          --normalObjectCount;
        }
        let insIndex = 0;
        for (; insIndex < normalObjectCount; ++insIndex) {
          instances[insIndex] = deserializeCCObject(data, instances[insIndex]);
        }
        const classes = data[3];
        for (let typeIndex = 0; typeIndex < instanceTypesLen; ++typeIndex, ++insIndex) {
          let type = instanceTypes[typeIndex];
          const eachData = instances[insIndex];
          if (type >= 0) {
            const ctor = classes[type];
            instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData);
          } else {
            type = ~type;
            const 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) {
        let klass = classFinder(type);
        if (!klass) {
          if (silent) {
            container[index] = ((c, i, t) => function proxy() {
              const 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) {
        const classFinder = customFinder || getClassById;
        const classes = data[3];
        for (let i = 0; i < classes.length; ++i) {
          const klassLayout = classes[i];
          if (typeof klassLayout !== 'string') {
            {
              if (typeof klassLayout[CLASS_TYPE] === 'function') {
                throw new Error('Can not deserialize the same JSON data again.');
              }
            }
            const 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) {
        const masks = data[4];
        if (masks) {
          const classes = data[3];
          for (let i = 0; i < masks.length; ++i) {
            const mask = masks[i];
            mask[MASK_CLASS] = classes[mask[MASK_CLASS]];
          }
        }
      }
      function parseResult(data) {
        const instances = data[5];
        const sharedStrings = data[2];
        const dependSharedUuids = data[1];
        const dependObjs = data[8];
        const dependKeys = data[9];
        const dependUuids = data[10];
        for (let i = 0; i < dependObjs.length; ++i) {
          const obj = dependObjs[i];
          if (typeof obj === 'number') {
            dependObjs[i] = instances[obj];
          }
          let key = dependKeys[i];
          if (typeof key === 'number') {
            if (key >= 0) {
              key = sharedStrings[key];
            } else {
              key = ~key;
            }
            dependKeys[i] = key;
          }
          const uuid = dependUuids[i];
          if (typeof uuid === 'number') {
            dependUuids[i] = dependSharedUuids[uuid];
          }
        }
      }
      function isCompiledJson(json) {
        if (Array.isArray(json)) {
          const 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 = {};
        let version = data[0];
        let preprocessed = false;
        if (typeof version === 'object') {
          preprocessed = version.preprocessed;
          version = version.version;
        }
        if (version < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, version));
        }
        const context = options;
        context._version = version;
        context.result = details;
        data[0] = 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);
        }
        let isBorrowedDetails = false;
        if (!details) {
          const borrowedDetails = Details.pool.get();
          assertIsTrue(borrowedDetails, `Can not allocate deserialization details`);
          details = borrowedDetails;
          isBorrowedDetails = true;
        }
        let res;
        if (!isCompiledJson(data)) {
          res = deserializeDynamic(data, details, options);
        } else {
          initializeDeserializationContext(data, details, options);
          const runtimeData = data;
          cclegacy.game._isCloning = true;
          const instances = runtimeData[5];
          const rootIndex = parseInstances(runtimeData);
          cclegacy.game._isCloning = false;
          if (runtimeData[7]) {
            dereference(runtimeData[7], instances, runtimeData[2]);
          }
          parseResult(runtimeData);
          res = instances[rootIndex];
        }
        if (isBorrowedDetails) {
          Details.pool.put(details);
        }
        return res;
      }
      deserialize.Details = Details;
      deserialize.reportMissingClass = reportMissingClass;
      class FileInfo {
        constructor(version) {
          this.preprocessed = true;
          this.version = version;
        }
      }
      function unpackJSONs(data, classFinder, reportMissingClass) {
        if (data[0] < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, data[0]));
        }
        lookupClasses(data, true, classFinder, deserialize.reportMissingClass);
        cacheMasks(data);
        const version = new FileInfo(data[0]);
        const sharedUuids = data[1];
        const sharedStrings = data[2];
        const sharedClasses = data[3];
        const sharedMasks = data[4];
        const sections = data[PACKED_SECTIONS];
        for (let i = 0; i < sections.length; ++i) {
          const 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) {
        const instances = data[5];
        const rootInfo = instances[instances.length - 1];
        if (typeof rootInfo !== 'number') {
          return false;
        } else {
          return rootInfo < 0;
        }
      }
      function getDependUuidList(json) {
        const sharedUuids = json[1];
        return json[10].map(index => sharedUuids[index]);
      }
      function parseUuidDependencies(serialized) {
        {
          return getDependUuidList(serialized);
        }
      }
      cclegacy.deserialize = deserialize;

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

      function deserializeAsset(json, options) {
        let classFinder;
        {
          classFinder = MissingScript.safeFindClass;
        }
        const tdInfo = Details.pool.get();
        let asset;
        try {
          asset = deserialize(json, tdInfo, {
            classFinder,
            customEnv: options
          });
        } catch (e) {
          error(e);
          Details.pool.put(tdInfo);
          throw e;
        }
        asset._uuid = options.__uuid__ || '';
        const uuidList = tdInfo.uuidList;
        const objList = tdInfo.uuidObjList;
        const propList = tdInfo.uuidPropList;
        const typeList = tdInfo.uuidTypeList || [];
        const depends = [];
        for (let i = 0; i < uuidList.length; i++) {
          const 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;
      }

      class DependUtil {
        static get instance() {
          if (!this._instance) {
            this._instance = new DependUtil();
          }
          return this._instance;
        }
        constructor() {
          this._depends = new Cache();
        }
        init() {
          this._depends.clear();
        }
        getNativeDep(uuid) {
          const depend = this._depends.get(uuid);
          if (depend && depend.nativeDep) {
            return {
              ...depend.nativeDep
            };
          }
          return null;
        }
        getDeps(uuid) {
          if (this._depends.has(uuid)) {
            return this._depends.get(uuid).deps;
          }
          return [];
        }
        getDepsRecursively(uuid) {
          const exclude = Object.create(null);
          const depends = [];
          this._descend(uuid, exclude, depends);
          return depends;
        }
        remove(uuid) {
          this._depends.remove(uuid);
        }
        parse(uuid, json) {
          let 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 {
                const 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;
        }
        _parseDepsFromAsset(asset) {
          const out = {
            deps: [],
            parsedFromExistAsset: true
          };
          const deps = dependMap.get(asset);
          assertIsNonNullable(deps);
          for (let i = 0, l = deps.length; i < l; i++) {
            out.deps.push(deps[i].uuid);
          }
          if (nativeDependMap.has(asset)) {
            out.nativeDep = asset._nativeDep;
          }
          return out;
        }
        _parseDepsFromJson(json) {
          const depends = parseUuidDependencies(json);
          depends.forEach((uuid, index) => depends[index] = decodeUuid(uuid));
          return depends;
        }
        _descend(uuid, exclude, depends) {
          const deps = this.getDeps(uuid);
          for (let i = 0; i < deps.length; i++) {
            const depend = deps[i];
            if (!exclude[depend]) {
              exclude[depend] = true;
              depends.push(depend);
              this._descend(depend, exclude, depends);
            }
          }
        }
      }
      DependUtil._instance = void 0;
      var dependUtil = DependUtil.instance;

      const textureBaseProto$1 = jsb.TextureBase.prototype;
      textureBaseProto$1._serialize = function (ctxForExporting) {
        return '';
      };
      textureBaseProto$1._deserialize = function (serializedData, handle) {
        const data = serializedData;
        const 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]));
        }
      };
      textureBaseProto$1._getGFXDevice = function () {
        return deviceManager.gfxDevice;
      };
      textureBaseProto$1._getGFXFormat = function () {
        return this._getGFXPixelFormat(this.format);
      };
      textureBaseProto$1._setGFXFormat = function (format) {
        this.format = format === undefined ? 35 : format;
      };
      textureBaseProto$1._getGFXPixelFormat = function (format) {
        if (format === 1026) {
          format = 72;
        } else if (format === 1025) {
          format = 85;
        } else if (format === 1024) {
          format = 83;
        }
        return format;
      };
      textureBaseProto$1.createNode = null;
      const TextureBase = jsb.TextureBase;
      TextureBase.Filter = TextureFilter;
      TextureBase.PixelFormat = PixelFormat;
      TextureBase.WrapMode = WrapMode$1;
      textureBaseProto$1._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._gfxSampler = null;
        this._samplerInfo = null;
        this._textureHash = 0;
        this._registerGFXSamplerUpdatedListener();
      };
      const oldGetGFXSampler = textureBaseProto$1.getGFXSampler;
      textureBaseProto$1.getGFXSampler = function () {
        if (!this._gfxSampler) {
          this._gfxSampler = oldGetGFXSampler.call(this);
        }
        return this._gfxSampler;
      };
      const oldGetHash = textureBaseProto$1.getHash;
      textureBaseProto$1.getHash = function () {
        if (this._textureHash === 0) {
          this._textureHash = oldGetHash.call(this);
        }
        return this._textureHash;
      };
      const oldGetSamplerInfo = textureBaseProto$1.getSamplerInfo;
      textureBaseProto$1.getSamplerInfo = function () {
        if (!this._samplerInfo) {
          this._samplerInfo = oldGetSamplerInfo.call(this);
        }
        return this._samplerInfo;
      };
      const oldDestroy$1 = textureBaseProto$1.destroy;
      textureBaseProto$1.destroy = function () {
        var _cclegacy$director$ro;
        if ((_cclegacy$director$ro = cclegacy.director.root) !== null && _cclegacy$director$ro !== void 0 && _cclegacy$director$ro.batcher2D) {
          cclegacy.director.root.batcher2D._releaseDescriptorSetCache(this.getGFXTexture(), this.getGFXSampler());
        }
        return oldDestroy$1.call(this);
      };
      textureBaseProto$1._onGFXSamplerUpdated = function (gfxSampler, samplerInfo) {
        this._gfxSampler = gfxSampler;
        this._samplerInfo = samplerInfo;
      };
      cclegacy.TextureBase = jsb.TextureBase;
      patch_cc_TextureBase({
        TextureBase,
        Filter: TextureFilter,
        WrapMode: WrapMode$1,
        PixelFormat
      });

      const SimpleTexture = jsb.SimpleTexture;
      const jsbWindow = jsb.window;
      SimpleTexture.Filter = TextureFilter;
      SimpleTexture.PixelFormat = PixelFormat;
      SimpleTexture.WrapMode = WrapMode$1;
      const simpleTextureProto = jsb.SimpleTexture.prototype;
      const oldUpdateDataFunc = simpleTextureProto.uploadData;
      simpleTextureProto.uploadData = function (source, level = 0, arrayIndex = 0) {
        let data;
        if (source instanceof jsbWindow.HTMLCanvasElement) {
          data = source.data;
        } else if (source instanceof jsbWindow.HTMLImageElement) {
          data = source._data;
        } else if (ArrayBuffer.isView(source)) {
          data = source.buffer;
        }
        oldUpdateDataFunc.call(this, data, level, arrayIndex);
      };
      simpleTextureProto._ctor = function () {
        jsb.TextureBase.prototype._ctor.apply(this, arguments);
        this._gfxTexture = null;
        this._registerListeners();
      };
      const oldGetGFXTexture = simpleTextureProto.getGFXTexture;
      simpleTextureProto.getGFXTexture = function () {
        if (!this._gfxTexture) {
          this._gfxTexture = oldGetGFXTexture.call(this);
        }
        return this._gfxTexture;
      };
      simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
        this._gfxTexture = gfxTexture;
      };
      simpleTextureProto._onAfterAssignImage = function (image) {
        if (macro.CLEANUP_IMAGE_CACHE) {
          const deps = dependUtil.getDeps(this._uuid);
          const index = deps.indexOf(image._uuid);
          if (index !== -1) {
            fastRemoveAt$2(deps, index);
            image.decRef();
          }
        }
      };
      patch_cc_SimpleTexture({
        SimpleTexture
      });
      cclegacy.SimpleTexture = jsb.SimpleTexture;

      const texture2DProto = jsb.Texture2D.prototype;
      texture2DProto.createNode = null;
      const Texture2D$1 = exports("Texture2D", jsb.Texture2D);
      Texture2D$1.Filter = TextureFilter;
      Texture2D$1.PixelFormat = PixelFormat;
      Texture2D$1.WrapMode = WrapMode$1;
      texture2DProto._ctor = function () {
        SimpleTexture.prototype._ctor.apply(this, arguments);
        this._mipmaps = [];
      };
      texture2DProto._serialize = function (ctxForExporting) {
        return null;
      };
      texture2DProto._deserialize = function (serializedData, handle) {
        const data = serializedData;
        TextureBase.prototype._deserialize.call(this, data.base, undefined);
        this._mipmaps = new Array(data.mipmaps.length);
        for (let i = 0; i < data.mipmaps.length; ++i) {
          this._mipmaps[i] = new ImageAsset$1();
          if (!data.mipmaps[i]) {
            continue;
          }
          const mipmapUUID = data.mipmaps[i];
          handle.result.push(this._mipmaps, `${i}`, mipmapUUID, getClassId(ImageAsset$1));
        }
      };
      const oldOnLoaded$2 = texture2DProto.onLoaded;
      texture2DProto.onLoaded = function () {
        this.syncMipmapsForJS(this._mipmaps);
        oldOnLoaded$2.call(this);
      };
      Object.defineProperty(texture2DProto, 'image', {
        configurable: true,
        enumerable: true,
        get() {
          return this._mipmaps.length === 0 ? null : this._mipmaps[0];
        },
        set(value) {
          this.mipmaps = value ? [value] : [];
        }
      });
      Object.defineProperty(texture2DProto, 'mipmaps', {
        configurable: true,
        enumerable: true,
        get() {
          return this._mipmaps;
        },
        set(arr) {
          for (let i = 0, len = arr.length; i < len; ++i) {
            arr[i]._syncDataToNative();
          }
          this._mipmaps = arr;
          this.setMipmaps(arr);
        }
      });
      cclegacy.Texture2D = jsb.Texture2D;
      patch_cc_Texture2D({
        Texture2D: Texture2D$1,
        ImageAsset: ImageAsset$1
      });

      const space$1 = 2;
      class Atlas {
        constructor(width, height) {
          this._innerTextureInfos = {};
          this._innerSpriteFrames = [];
          this._count = 0;
          const 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;
        }
        insertSpriteFrame(spriteFrame) {
          const rect = spriteFrame.rect;
          const texture = spriteFrame.texture;
          const info = this._innerTextureInfos[texture.getId()];
          let sx = rect.x;
          let sy = rect.y;
          if (info) {
            sx += info.x;
            sy += info.y;
          } else {
            const width = texture.width;
            const 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 (cclegacy.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
            };
            this._count++;
            sx += this._x;
            sy += this._y;
            this._x += width + space$1;
          }
          const frame = {
            x: sx,
            y: sy,
            texture: this._texture
          };
          this._innerSpriteFrames.push(spriteFrame);
          return frame;
        }
        removeSpriteFrame(spriteFrame) {
          fastRemove(this._innerSpriteFrames, spriteFrame);
        }
        deleteInnerTexture(texture) {
          if (texture && this._innerTextureInfos[texture.getId()]) {
            delete this._innerTextureInfos[texture.getId()];
            this._count--;
          }
        }
        isEmpty() {
          return this._count <= 0;
        }
        reset() {
          this._x = space$1;
          this._y = space$1;
          this._nextY = space$1;
          const frames = this._innerSpriteFrames;
          for (let i = 0, l = frames.length; i < l; i++) {
            const frame = frames[i];
            if (!frame.isValid) {
              continue;
            }
            frame._resetDynamicAtlasFrame();
          }
          this._innerSpriteFrames.length = 0;
          this._innerTextureInfos = {};
        }
        destroy() {
          this.reset();
          this._texture.destroy();
        }
      } exports("Atlas", Atlas);
      class DynamicAtlasTexture extends Texture2D$1 {
        initWithSize(width, height, format = 35) {
          this.reset({
            width,
            height,
            format
          });
        }
        drawTextureAt(image, x, y) {
          const gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          const gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            warnID(16363);
            return;
          }
          const 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]);
        }
      }

      const SceneAsset = exports("SceneAsset", jsb.SceneAsset);
      cclegacy.SceneAsset = SceneAsset;
      const sceneAssetProto = SceneAsset.prototype;
      Object.defineProperty(sceneAssetProto, 'scene', {
        enumerable: true,
        configurable: true,
        get() {
          if (!this._scene) {
            this._scene = this.getScene();
          }
          return this._scene;
        },
        set(v) {
          this._scene = v;
          this.setScene(v);
        }
      });
      sceneAssetProto._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._scene = null;
      };
      patch_cc_SceneAsset({
        SceneAsset
      });

      deprecateModuleExportedName({
        SystemEventType: {
          newName: 'Input.EventType',
          since: '3.3.0',
          removed: false
        }
      });

      deprecateModuleExportedName({
        SystemEvent: {
          newName: 'Input',
          since: '3.4.0',
          removed: false
        },
        systemEvent: {
          newName: 'input',
          since: '3.4.0',
          removed: false
        }
      });

      class Event {
        constructor(type, bubbles) {
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = 0;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
          this.type = type;
          this.bubbles = !!bubbles;
        }
        unuse() {
          this.type = Event.NO_TYPE;
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = Event.NONE;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
        }
        reuse(type, bubbles) {
          this.type = type;
          this.bubbles = bubbles || false;
        }
        isStopped() {
          return this.propagationStopped || this.propagationImmediateStopped;
        }
        getCurrentTarget() {
          return this.currentTarget;
        }
        getType() {
          return this.type;
        }
      } exports("Event", 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;
      cclegacy.Event = Event;

      class EventAcceleration extends Event {
        constructor(acc, bubbles) {
          super("devicemotion", bubbles);
          this.acc = acc;
        }
      } exports("EventAcceleration", EventAcceleration);
      Event.EventAcceleration = EventAcceleration;

      class EventKeyboard extends Event {
        get isPressed() {
          return this._isPressed;
        }
        constructor(keyCode, eventType, bubbles) {
          if (typeof eventType === 'boolean') {
            const isPressed = eventType;
            eventType = isPressed ? "keydown" : "keyup";
          }
          super(eventType, bubbles);
          this.rawEvent = void 0;
          this._isPressed = eventType !== "keyup";
          if (typeof keyCode === 'number') {
            this.keyCode = keyCode;
          } else {
            this.keyCode = keyCode.keyCode;
            this.rawEvent = keyCode;
          }
          this.windowId = 0;
        }
      } exports("EventKeyboard", EventKeyboard);
      Event.EventKeyboard = EventKeyboard;

      class EventMouse extends Event {
        get eventType() {
          return this._eventType;
        }
        constructor(eventType, bubbles, prevLoc, windowId) {
          super(eventType, bubbles);
          this.movementX = 0;
          this.movementY = 0;
          this.windowId = 0;
          this.preventSwallow = false;
          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;
        }
        setScrollData(scrollX, scrollY) {
          this._scrollX = scrollX;
          this._scrollY = scrollY;
        }
        getScrollX() {
          return this._scrollX;
        }
        getScrollY() {
          return this._scrollY;
        }
        setLocation(x, y) {
          this._x = x;
          this._y = y;
        }
        getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          return out;
        }
        getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, cclegacy.view._designResolutionSize.height - this._y);
          return out;
        }
        getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          cclegacy.view._convertToUISpace(out);
          return out;
        }
        getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          return out;
        }
        getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          cclegacy.view._convertToUISpace(out);
          return out;
        }
        getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x - this._prevX, this._y - this._prevY);
          return out;
        }
        getDeltaX() {
          return this._x - this._prevX;
        }
        getDeltaY() {
          return this._y - this._prevY;
        }
        getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          const view = cclegacy.view;
          Vec2.set(out, (this._x - this._prevX) / view.getScaleX(), (this._y - this._prevY) / view.getScaleY());
          return out;
        }
        getUIDeltaX() {
          return (this._x - this._prevX) / cclegacy.view.getScaleX();
        }
        getUIDeltaY() {
          return (this._y - this._prevY) / cclegacy.view.getScaleY();
        }
        setButton(button) {
          this._button = button;
        }
        getButton() {
          return this._button;
        }
        getLocationX() {
          return this._x;
        }
        getLocationY() {
          return this._y;
        }
        getUILocationX() {
          const view = cclegacy.view;
          const viewport = view.getViewportRect();
          return (this._x - viewport.x) / view.getScaleX();
        }
        getUILocationY() {
          const view = cclegacy.view;
          const viewport = view.getViewportRect();
          return (this._y - viewport.y) / view.getScaleY();
        }
      } exports("EventMouse", EventMouse);
      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;

      const _vec2$2 = new Vec2();
      class EventTouch extends Event {
        constructor(changedTouches, bubbles, eventType, touches = []) {
          super(eventType, bubbles);
          this.touch = null;
          this.simulate = false;
          this.windowId = 0;
          this.preventSwallow = false;
          this._eventCode = eventType;
          this._touches = changedTouches || [];
          this._allTouches = touches;
        }
        getEventCode() {
          return this._eventCode;
        }
        getTouches() {
          return this._touches;
        }
        getAllTouches() {
          return this._allTouches;
        }
        setLocation(x, y) {
          if (this.touch) {
            this.touch.setTouchInfo(this.touch.getID(), x, y);
          }
        }
        getLocation(out) {
          return this.touch ? this.touch.getLocation(out) : new Vec2();
        }
        getUILocation(out) {
          return this.touch ? this.touch.getUILocation(out) : new Vec2();
        }
        getLocationInView(out) {
          return this.touch ? this.touch.getLocationInView(out) : new Vec2();
        }
        getPreviousLocation(out) {
          return this.touch ? this.touch.getPreviousLocation(out) : new Vec2();
        }
        getStartLocation(out) {
          return this.touch ? this.touch.getStartLocation(out) : new Vec2();
        }
        getUIStartLocation(out) {
          return this.touch ? this.touch.getUIStartLocation(out) : new Vec2();
        }
        getID() {
          return this.touch ? this.touch.getID() : null;
        }
        getDelta(out) {
          return this.touch ? this.touch.getDelta(out) : new Vec2();
        }
        getUIDelta(out) {
          return this.touch ? this.touch.getUIDelta(out) : new Vec2();
        }
        getDeltaX() {
          return this.touch ? this.touch.getDelta(_vec2$2).x : 0;
        }
        getDeltaY() {
          return this.touch ? this.touch.getDelta(_vec2$2).y : 0;
        }
        getLocationX() {
          return this.touch ? this.touch.getLocationX() : 0;
        }
        getLocationY() {
          return this.touch ? this.touch.getLocationY() : 0;
        }
      } exports("EventTouch", EventTouch);
      EventTouch.MAX_TOUCHES = 5;
      Event.EventTouch = EventTouch;

      class EventGamepad extends Event {
        constructor(type, gamepad) {
          super(type, false);
          this.gamepad = gamepad;
        }
      } exports("EventGamepad", EventGamepad);

      class EventHandle extends Event {
        constructor(eventType, handleInputDevice) {
          super(eventType, false);
          this.handleInputDevice = handleInputDevice;
        }
      } exports("EventHandle", EventHandle);

      class EventHMD extends Event {
        constructor(eventType, hmdInputDevice) {
          super(eventType, false);
          this.hmdInputDevice = hmdInputDevice;
        }
      } exports("EventHMD", EventHMD);

      class EventHandheld extends Event {
        constructor(eventType, handheldInputDevice) {
          super(eventType, false);
          this.handheldInputDevice = handheldInputDevice;
        }
      } exports("EventHandheld", EventHandheld);

      class Acceleration {
        constructor(x = 0, y = 0, z = 0, timestamp = 0) {
          this.x = x;
          this.y = y;
          this.z = z;
          this.timestamp = timestamp;
        }
      } exports("Acceleration", Acceleration);

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

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

      const _vec2$1 = new Vec2();
      class Touch {
        get lastModified() {
          return this._lastModified;
        }
        constructor(x, y, 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);
        }
        getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          return out;
        }
        getLocationX() {
          return this._point.x;
        }
        getLocationY() {
          return this._point.y;
        }
        getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          cclegacy.view._convertToUISpace(out);
          return out;
        }
        getUILocationX() {
          const view = cclegacy.view;
          const viewport = view.getViewportRect();
          return (this._point.x - viewport.x) / view.getScaleX();
        }
        getUILocationY() {
          const view = cclegacy.view;
          const viewport = view.getViewportRect();
          return (this._point.y - viewport.y) / view.getScaleY();
        }
        getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          return out;
        }
        getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          cclegacy.view._convertToUISpace(out);
          return out;
        }
        getStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          return out;
        }
        getUIStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          cclegacy.view._convertToUISpace(out);
          return out;
        }
        getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point);
          out.subtract(this._prevPoint);
          return out;
        }
        getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          _vec2$1.set(this._point);
          _vec2$1.subtract(this._prevPoint);
          const view = cclegacy.view;
          out.set(view.getScaleX(), view.getScaleY());
          Vec2.divide(out, _vec2$1, out);
          return out;
        }
        getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, cclegacy.view._designResolutionSize.height - this._point.y);
          return out;
        }
        getPreviousLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, cclegacy.view._designResolutionSize.height - this._prevPoint.y);
          return out;
        }
        getStartLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, cclegacy.view._designResolutionSize.height - this._startPoint.y);
          return out;
        }
        getID() {
          return this._id;
        }
        setTouchInfo(id = 0, x = 0, y = 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;
          }
        }
        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 = cclegacy.game.frameStartTime;
        }
        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 = cclegacy.game.frameStartTime;
        }
        clone() {
          const touchID = this.getID();
          this.getStartLocation(_vec2$1);
          const clonedTouch = new Touch(_vec2$1.x, _vec2$1.y, touchID);
          this.getLocation(_vec2$1);
          clonedTouch.setPoint(_vec2$1.x, _vec2$1.y);
          this.getPreviousLocation(_vec2$1);
          clonedTouch.setPrevPoint(_vec2$1);
          return clonedTouch;
        }
      } exports("Touch", Touch);
      cclegacy.Touch = Touch;

      class AccelerometerInputSource {
        constructor() {
          this._intervalInSeconds = 0.2;
          this._intervalId = void 0;
          this._isEnabled = false;
          this._eventTarget = new EventTarget();
          this._didAccelerateFunc = this._didAccelerate.bind(this);
        }
        _didAccelerate() {
          const deviceMotionValue = jsb.device.getDeviceMotionValue();
          let x = deviceMotionValue[3] * 0.1;
          let y = deviceMotionValue[4] * 0.1;
          const z = deviceMotionValue[5] * 0.1;
          const orientation = screenAdapter.orientation;
          const tmpX = x;
          if (orientation === Orientation$1.LANDSCAPE_RIGHT) {
            x = -y;
            y = tmpX;
          } else if (orientation === Orientation$1.LANDSCAPE_LEFT) {
            x = y;
            y = -tmpX;
          } else if (orientation === Orientation$1.PORTRAIT_UPSIDE_DOWN) {
            x = -x;
            y = -y;
          }
          if (systemInfo.os === OS.ANDROID || systemInfo.os === OS.OHOS || systemInfo.os === OS.OPENHARMONY) {
            x = -x;
            y = -y;
          }
          const timestamp = performance.now();
          const acceleration = new Acceleration(x, y, z, timestamp);
          const eventAcceleration = new EventAcceleration(acceleration);
          this._eventTarget.emit("devicemotion", eventAcceleration);
        }
        start() {
          if (this._intervalId) {
            clearInterval(this._intervalId);
          }
          this._intervalId = setInterval(this._didAccelerateFunc, this._intervalInSeconds * 1000);
          jsb.device.setAccelerometerInterval(this._intervalInSeconds);
          jsb.device.setAccelerometerEnabled(true);
          this._isEnabled = true;
        }
        stop() {
          if (this._intervalId) {
            clearInterval(this._intervalId);
            this._intervalId = undefined;
          }
          jsb.device.setAccelerometerEnabled(false);
          this._isEnabled = false;
        }
        setInterval(intervalInMileseconds) {
          this._intervalInSeconds = intervalInMileseconds / 1000;
          jsb.device.setAccelerometerInterval(this._intervalInSeconds);
          if (this._isEnabled) {
            jsb.device.setAccelerometerEnabled(false);
            jsb.device.setAccelerometerEnabled(true);
          }
        }
        on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
      }

      class InputSource {}
      class InputSourceAxis1D extends InputSource {
        getValue() {
          throw new Error('Method not implemented.');
        }
      }
      class InputSourceAxis2D extends InputSource {
        getValue() {
          throw new Error('Method not implemented.');
        }
      }
      class InputSourceAxis3D extends InputSource {
        getValue() {
          throw new Error('Method not implemented.');
        }
      }
      class InputSourceQuat extends InputSource {
        getValue() {
          throw new Error('Method not implemented.');
        }
      }
      class CompositeInputSourceAxis1D extends InputSourceAxis1D {
        constructor(options) {
          super();
          this.positive = options.positive;
          this.negative = options.negative;
        }
        getValue() {
          const positiveValue = this.positive.getValue();
          const negativeValue = this.negative.getValue();
          if (Math.abs(positiveValue) > Math.abs(negativeValue)) {
            return positiveValue;
          }
          return -negativeValue;
        }
      }
      class CompositeInputSourceAxis2D extends InputSourceAxis2D {
        constructor(options) {
          super();
          this.up = options.up;
          this.down = options.down;
          this.left = options.left;
          this.right = options.right;
          this.xAxis = new CompositeInputSourceAxis1D({
            positive: this.right,
            negative: this.left
          });
          this.yAxis = new CompositeInputSourceAxis1D({
            positive: this.up,
            negative: this.down
          });
        }
        getValue() {
          return new Vec2(this.xAxis.getValue(), this.yAxis.getValue());
        }
      }
      class InputSourceButton extends InputSourceAxis1D {
        getValue() {
          return super.getValue();
        }
      }
      class InputSourceDpad extends CompositeInputSourceAxis2D {}
      class InputSourceStick extends CompositeInputSourceAxis2D {}
      class InputSourceOrientation extends InputSourceQuat {
        getValue() {
          return super.getValue();
        }
      }
      class InputSourcePosition extends InputSourceAxis3D {
        getValue() {
          return super.getValue();
        }
      }
      class InputSourceTouch extends InputSourceAxis1D {
        getValue() {
          return super.getValue();
        }
      }

      var Button$2;
      (function (Button) {
        Button[Button["BUTTON_SOUTH"] = 0] = "BUTTON_SOUTH";
        Button[Button["BUTTON_EAST"] = 1] = "BUTTON_EAST";
        Button[Button["BUTTON_WEST"] = 2] = "BUTTON_WEST";
        Button[Button["BUTTON_NORTH"] = 3] = "BUTTON_NORTH";
        Button[Button["NS_MINUS"] = 4] = "NS_MINUS";
        Button[Button["NS_PLUS"] = 5] = "NS_PLUS";
        Button[Button["BUTTON_L1"] = 6] = "BUTTON_L1";
        Button[Button["BUTTON_L2"] = 7] = "BUTTON_L2";
        Button[Button["BUTTON_L3"] = 8] = "BUTTON_L3";
        Button[Button["BUTTON_R1"] = 9] = "BUTTON_R1";
        Button[Button["BUTTON_R2"] = 10] = "BUTTON_R2";
        Button[Button["BUTTON_R3"] = 11] = "BUTTON_R3";
        Button[Button["DPAD_UP"] = 12] = "DPAD_UP";
        Button[Button["DPAD_DOWN"] = 13] = "DPAD_DOWN";
        Button[Button["DPAD_LEFT"] = 14] = "DPAD_LEFT";
        Button[Button["DPAD_RIGHT"] = 15] = "DPAD_RIGHT";
        Button[Button["LEFT_STICK_UP"] = 16] = "LEFT_STICK_UP";
        Button[Button["LEFT_STICK_DOWN"] = 17] = "LEFT_STICK_DOWN";
        Button[Button["LEFT_STICK_LEFT"] = 18] = "LEFT_STICK_LEFT";
        Button[Button["LEFT_STICK_RIGHT"] = 19] = "LEFT_STICK_RIGHT";
        Button[Button["RIGHT_STICK_UP"] = 20] = "RIGHT_STICK_UP";
        Button[Button["RIGHT_STICK_DOWN"] = 21] = "RIGHT_STICK_DOWN";
        Button[Button["RIGHT_STICK_LEFT"] = 22] = "RIGHT_STICK_LEFT";
        Button[Button["RIGHT_STICK_RIGHT"] = 23] = "RIGHT_STICK_RIGHT";
        Button[Button["ROKID_MENU"] = 24] = "ROKID_MENU";
        Button[Button["ROKID_START"] = 25] = "ROKID_START";
      })(Button$2 || (Button$2 = {}));
      const _nativeButtonMap$1 = {
        1: Button$2.BUTTON_EAST,
        2: Button$2.BUTTON_SOUTH,
        3: Button$2.BUTTON_NORTH,
        4: Button$2.BUTTON_WEST,
        5: Button$2.BUTTON_L1,
        6: Button$2.BUTTON_R1,
        7: Button$2.NS_MINUS,
        8: Button$2.NS_PLUS,
        9: Button$2.BUTTON_L3,
        10: Button$2.BUTTON_R3,
        11: Button$2.ROKID_MENU,
        12: Button$2.ROKID_START
      };
      class GamepadInputDevice {
        get buttonNorth() {
          return this._buttonNorth;
        }
        get buttonEast() {
          return this._buttonEast;
        }
        get buttonWest() {
          return this._buttonWest;
        }
        get buttonSouth() {
          return this._buttonSouth;
        }
        get buttonL1() {
          return this._buttonL1;
        }
        get buttonL2() {
          return this._buttonL2;
        }
        get buttonL3() {
          return this._buttonL3;
        }
        get buttonR1() {
          return this._buttonR1;
        }
        get buttonR2() {
          return this._buttonR2;
        }
        get buttonR3() {
          return this._buttonR3;
        }
        get buttonShare() {
          return this._buttonShare;
        }
        get buttonOptions() {
          return this._buttonOptions;
        }
        get dpad() {
          return this._dpad;
        }
        get leftStick() {
          return this._leftStick;
        }
        get rightStick() {
          return this._rightStick;
        }
        get buttonStart() {
          return this._buttonStart;
        }
        get gripLeft() {
          return this._gripLeft;
        }
        get gripRight() {
          return this._gripRight;
        }
        get handLeftPosition() {
          return this._handLeftPosition;
        }
        get handLeftOrientation() {
          return this._handLeftOrientation;
        }
        get handRightPosition() {
          return this._handRightPosition;
        }
        get handRightOrientation() {
          return this._handRightOrientation;
        }
        get aimLeftPosition() {
          return this._aimLeftPosition;
        }
        get aimLeftOrientation() {
          return this._aimLeftOrientation;
        }
        get aimRightPosition() {
          return this._aimRightPosition;
        }
        get aimRightOrientation() {
          return this._aimRightOrientation;
        }
        get deviceId() {
          return this._deviceId;
        }
        get connected() {
          return this._connected;
        }
        constructor(deviceId) {
          this._deviceId = -1;
          this._connected = false;
          this._nativeButtonState = {
            [Button$2.BUTTON_SOUTH]: 0,
            [Button$2.BUTTON_EAST]: 0,
            [Button$2.BUTTON_WEST]: 0,
            [Button$2.BUTTON_NORTH]: 0,
            [Button$2.NS_MINUS]: 0,
            [Button$2.NS_PLUS]: 0,
            [Button$2.BUTTON_L1]: 0,
            [Button$2.BUTTON_L2]: 0,
            [Button$2.BUTTON_L3]: 0,
            [Button$2.BUTTON_R1]: 0,
            [Button$2.BUTTON_R2]: 0,
            [Button$2.BUTTON_R3]: 0,
            [Button$2.DPAD_UP]: 0,
            [Button$2.DPAD_DOWN]: 0,
            [Button$2.DPAD_LEFT]: 0,
            [Button$2.DPAD_RIGHT]: 0,
            [Button$2.LEFT_STICK_UP]: 0,
            [Button$2.LEFT_STICK_DOWN]: 0,
            [Button$2.LEFT_STICK_LEFT]: 0,
            [Button$2.LEFT_STICK_RIGHT]: 0,
            [Button$2.RIGHT_STICK_UP]: 0,
            [Button$2.RIGHT_STICK_DOWN]: 0,
            [Button$2.RIGHT_STICK_LEFT]: 0,
            [Button$2.RIGHT_STICK_RIGHT]: 0,
            [Button$2.ROKID_MENU]: 0,
            [Button$2.ROKID_START]: 0
          };
          this._deviceId = deviceId;
          this._initInputSource();
        }
        static _init() {
          if (!systemInfo.hasFeature(Feature$1.EVENT_GAMEPAD)) {
            return;
          }
          GamepadInputDevice._registerEvent();
        }
        static _on(eventType, cb, target) {
          GamepadInputDevice._eventTarget.on(eventType, cb, target);
        }
        static _removeInputDevice(id) {
          const removeIndex = GamepadInputDevice.all.findIndex(device => device.deviceId === id);
          if (removeIndex === -1) {
            return;
          }
          fastRemoveAt$2(GamepadInputDevice.all, removeIndex);
        }
        static _getInputDevice(id) {
          return GamepadInputDevice.all.find(device => device.deviceId === id);
        }
        static _createInputDevice(id, connected) {
          const device = new GamepadInputDevice(id);
          device._connected = connected;
          GamepadInputDevice.all.push(device);
          return device;
        }
        static _getOrCreateInputDevice(id, connected) {
          let device = GamepadInputDevice._getInputDevice(id);
          if (!device) {
            device = GamepadInputDevice._createInputDevice(id, connected);
          }
          device._connected = connected;
          return device;
        }
        static _registerEvent() {
          jsb.onControllerInput = infoList => {
            for (let i = 0; i < infoList.length; ++i) {
              const info = infoList[i];
              const device = GamepadInputDevice._getOrCreateInputDevice(info.id, true);
              device._updateNativeButtonState(info);
              GamepadInputDevice._eventTarget.emit("gamepad-input", new EventGamepad("gamepad-input", device));
            }
          };
          jsb.onControllerChange = controllerIds => {
            for (let i = 0; i < controllerIds.length; ++i) {
              const id = controllerIds[i];
              let device = GamepadInputDevice._getInputDevice(id);
              if (!device) {
                device = GamepadInputDevice._createInputDevice(id, true);
                GamepadInputDevice._eventTarget.emit("gamepad-change", new EventGamepad("gamepad-change", device));
              }
            }
            const allDevices = GamepadInputDevice.all;
            for (let i = 0; i < allDevices.length; ++i) {
              const device = allDevices[i];
              if (!controllerIds.includes(device.deviceId)) {
                GamepadInputDevice._removeInputDevice(device.deviceId);
                device._connected = false;
                GamepadInputDevice._eventTarget.emit("gamepad-change", new EventGamepad("gamepad-change", device));
              }
            }
          };
        }
        _axisToButtons(axisValue) {
          const 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
            };
          }
        }
        _updateNativeButtonState(info) {
          const {
            buttonInfoList,
            axisInfoList
          } = info;
          for (let i = 0; i < buttonInfoList.length; ++i) {
            const buttonInfo = buttonInfoList[i];
            const button = _nativeButtonMap$1[buttonInfo.code];
            this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0;
          }
          for (let i = 0; i < axisInfoList.length; ++i) {
            const axisInfo = axisInfoList[i];
            const {
              code,
              value
            } = axisInfo;
            let negativeButton;
            let positiveButton;
            let axisValue;
            switch (code) {
              case 1:
                negativeButton = Button$2.DPAD_LEFT;
                positiveButton = Button$2.DPAD_RIGHT;
                axisValue = this._axisToButtons(value);
                break;
              case 2:
                negativeButton = Button$2.DPAD_DOWN;
                positiveButton = Button$2.DPAD_UP;
                axisValue = this._axisToButtons(value);
                break;
              case 3:
                negativeButton = Button$2.LEFT_STICK_LEFT;
                positiveButton = Button$2.LEFT_STICK_RIGHT;
                axisValue = this._axisToButtons(value);
                break;
              case 4:
                negativeButton = Button$2.LEFT_STICK_DOWN;
                positiveButton = Button$2.LEFT_STICK_UP;
                axisValue = this._axisToButtons(value);
                break;
              case 5:
                negativeButton = Button$2.RIGHT_STICK_LEFT;
                positiveButton = Button$2.RIGHT_STICK_RIGHT;
                axisValue = this._axisToButtons(value);
                break;
              case 6:
                negativeButton = Button$2.RIGHT_STICK_DOWN;
                positiveButton = Button$2.RIGHT_STICK_UP;
                axisValue = this._axisToButtons(value);
                break;
              default:
                if (code === 7) {
                  this._nativeButtonState[Button$2.BUTTON_L2] = value;
                } else if (code === 8) {
                  this._nativeButtonState[Button$2.BUTTON_R2] = value;
                }
                break;
            }
            if (negativeButton && positiveButton && axisValue) {
              this._nativeButtonState[negativeButton] = axisValue.negative;
              this._nativeButtonState[positiveButton] = axisValue.positive;
            }
          }
        }
        _initInputSource() {
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = () => this._nativeButtonState[Button$2.BUTTON_NORTH];
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = () => this._nativeButtonState[Button$2.BUTTON_EAST];
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = () => this._nativeButtonState[Button$2.BUTTON_WEST];
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = () => this._nativeButtonState[Button$2.BUTTON_SOUTH];
          this._buttonL1 = new InputSourceButton();
          this._buttonL1.getValue = () => this._nativeButtonState[Button$2.BUTTON_L1];
          this._buttonL2 = new InputSourceButton();
          this._buttonL2.getValue = () => this._nativeButtonState[Button$2.BUTTON_L2];
          this._buttonL3 = new InputSourceButton();
          this._buttonL3.getValue = () => this._nativeButtonState[Button$2.BUTTON_L3];
          this._buttonR1 = new InputSourceButton();
          this._buttonR1.getValue = () => this._nativeButtonState[Button$2.BUTTON_R1];
          this._buttonR2 = new InputSourceButton();
          this._buttonR2.getValue = () => this._nativeButtonState[Button$2.BUTTON_R2];
          this._buttonR3 = new InputSourceButton();
          this._buttonR3.getValue = () => this._nativeButtonState[Button$2.BUTTON_R3];
          this._buttonShare = new InputSourceButton();
          this._buttonShare.getValue = () => this._nativeButtonState[Button$2.NS_MINUS];
          this._buttonOptions = new InputSourceButton();
          this._buttonOptions.getValue = () => this._nativeButtonState[Button$2.NS_PLUS] || this._nativeButtonState[Button$2.ROKID_MENU];
          const dpadUp = new InputSourceButton();
          dpadUp.getValue = () => this._nativeButtonState[Button$2.DPAD_UP];
          const dpadDown = new InputSourceButton();
          dpadDown.getValue = () => this._nativeButtonState[Button$2.DPAD_DOWN];
          const dpadLeft = new InputSourceButton();
          dpadLeft.getValue = () => this._nativeButtonState[Button$2.DPAD_LEFT];
          const dpadRight = new InputSourceButton();
          dpadRight.getValue = () => this._nativeButtonState[Button$2.DPAD_RIGHT];
          this._dpad = new InputSourceDpad({
            up: dpadUp,
            down: dpadDown,
            left: dpadLeft,
            right: dpadRight
          });
          const leftStickUp = new InputSourceButton();
          leftStickUp.getValue = () => this._nativeButtonState[Button$2.LEFT_STICK_UP];
          const leftStickDown = new InputSourceButton();
          leftStickDown.getValue = () => this._nativeButtonState[Button$2.LEFT_STICK_DOWN];
          const leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = () => this._nativeButtonState[Button$2.LEFT_STICK_LEFT];
          const leftStickRight = new InputSourceButton();
          leftStickRight.getValue = () => this._nativeButtonState[Button$2.LEFT_STICK_RIGHT];
          this._leftStick = new InputSourceStick({
            up: leftStickUp,
            down: leftStickDown,
            left: leftStickLeft,
            right: leftStickRight
          });
          const rightStickUp = new InputSourceButton();
          rightStickUp.getValue = () => this._nativeButtonState[Button$2.RIGHT_STICK_UP];
          const rightStickDown = new InputSourceButton();
          rightStickDown.getValue = () => this._nativeButtonState[Button$2.RIGHT_STICK_DOWN];
          const rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = () => this._nativeButtonState[Button$2.RIGHT_STICK_LEFT];
          const rightStickRight = new InputSourceButton();
          rightStickRight.getValue = () => this._nativeButtonState[Button$2.RIGHT_STICK_RIGHT];
          this._rightStick = new InputSourceStick({
            up: rightStickUp,
            down: rightStickDown,
            left: rightStickLeft,
            right: rightStickRight
          });
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = () => this._nativeButtonState[Button$2.ROKID_START];
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = () => 0;
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = () => 0;
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = () => Vec3.ZERO;
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = () => Quat.IDENTITY;
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = () => Vec3.ZERO;
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = () => Quat.IDENTITY;
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = () => Vec3.ZERO;
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = () => Quat.IDENTITY;
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = () => Vec3.ZERO;
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = () => Quat.IDENTITY;
        }
      }
      GamepadInputDevice.all = [];
      GamepadInputDevice.xr = null;
      GamepadInputDevice._eventTarget = new EventTarget();

      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 Pose$3;
      (function (Pose) {
        Pose[Pose["HAND_LEFT"] = 0] = "HAND_LEFT";
        Pose[Pose["HAND_RIGHT"] = 1] = "HAND_RIGHT";
        Pose[Pose["AIM_LEFT"] = 2] = "AIM_LEFT";
        Pose[Pose["AIM_RIGHT"] = 3] = "AIM_RIGHT";
      })(Pose$3 || (Pose$3 = {}));
      var StickKeyCode;
      (function (StickKeyCode) {
        StickKeyCode[StickKeyCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickKeyCode[StickKeyCode["A"] = 1] = "A";
        StickKeyCode[StickKeyCode["B"] = 2] = "B";
        StickKeyCode[StickKeyCode["X"] = 3] = "X";
        StickKeyCode[StickKeyCode["Y"] = 4] = "Y";
        StickKeyCode[StickKeyCode["L1"] = 5] = "L1";
        StickKeyCode[StickKeyCode["R1"] = 6] = "R1";
        StickKeyCode[StickKeyCode["MINUS"] = 7] = "MINUS";
        StickKeyCode[StickKeyCode["PLUS"] = 8] = "PLUS";
        StickKeyCode[StickKeyCode["L3"] = 9] = "L3";
        StickKeyCode[StickKeyCode["R3"] = 10] = "R3";
        StickKeyCode[StickKeyCode["MENU"] = 11] = "MENU";
        StickKeyCode[StickKeyCode["START"] = 12] = "START";
        StickKeyCode[StickKeyCode["TRIGGER_LEFT"] = 13] = "TRIGGER_LEFT";
        StickKeyCode[StickKeyCode["TRIGGER_RIGHT"] = 14] = "TRIGGER_RIGHT";
      })(StickKeyCode || (StickKeyCode = {}));
      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["L2"] = 7] = "L2";
        StickAxisCode[StickAxisCode["R2"] = 8] = "R2";
        StickAxisCode[StickAxisCode["LEFT_GRIP"] = 9] = "LEFT_GRIP";
        StickAxisCode[StickAxisCode["RIGHT_GRIP"] = 10] = "RIGHT_GRIP";
      })(StickAxisCode || (StickAxisCode = {}));
      var StickTouchCode;
      (function (StickTouchCode) {
        StickTouchCode[StickTouchCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickTouchCode[StickTouchCode["A"] = 1] = "A";
        StickTouchCode[StickTouchCode["B"] = 2] = "B";
        StickTouchCode[StickTouchCode["X"] = 3] = "X";
        StickTouchCode[StickTouchCode["Y"] = 4] = "Y";
        StickTouchCode[StickTouchCode["LEFT_TRIGGER"] = 5] = "LEFT_TRIGGER";
        StickTouchCode[StickTouchCode["RIGHT_TRIGGER"] = 6] = "RIGHT_TRIGGER";
        StickTouchCode[StickTouchCode["LEFT_THUMBSTICK"] = 7] = "LEFT_THUMBSTICK";
        StickTouchCode[StickTouchCode["RIGHT_THUMBSTICK"] = 8] = "RIGHT_THUMBSTICK";
      })(StickTouchCode || (StickTouchCode = {}));
      const _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
      };
      class HandleInputDevice {
        get buttonNorth() {
          return this._buttonNorth;
        }
        get buttonEast() {
          return this._buttonEast;
        }
        get buttonWest() {
          return this._buttonWest;
        }
        get buttonSouth() {
          return this._buttonSouth;
        }
        get buttonTriggerLeft() {
          return this._buttonTriggerLeft;
        }
        get buttonTriggerRight() {
          return this._buttonTriggerRight;
        }
        get triggerLeft() {
          return this._triggerLeft;
        }
        get triggerRight() {
          return this._triggerRight;
        }
        get gripLeft() {
          return this._gripLeft;
        }
        get gripRight() {
          return this._gripRight;
        }
        get leftStick() {
          return this._leftStick;
        }
        get rightStick() {
          return this._rightStick;
        }
        get buttonLeftStick() {
          return this._buttonLeftStick;
        }
        get buttonRightStick() {
          return this._buttonRightStick;
        }
        get buttonOptions() {
          return this._buttonOptions;
        }
        get buttonStart() {
          return this._buttonStart;
        }
        get handLeftPosition() {
          return this._handLeftPosition;
        }
        get handLeftOrientation() {
          return this._handLeftOrientation;
        }
        get handRightPosition() {
          return this._handRightPosition;
        }
        get handRightOrientation() {
          return this._handRightOrientation;
        }
        get aimLeftPosition() {
          return this._aimLeftPosition;
        }
        get aimLeftOrientation() {
          return this._aimLeftOrientation;
        }
        get aimRightPosition() {
          return this._aimRightPosition;
        }
        get aimRightOrientation() {
          return this._aimRightOrientation;
        }
        get touchButtonA() {
          return this._touchButtonA;
        }
        get touchButtonB() {
          return this._touchButtonB;
        }
        get touchButtonX() {
          return this._touchButtonX;
        }
        get touchButtonY() {
          return this._touchButtonY;
        }
        get touchButtonTriggerLeft() {
          return this._touchButtonTriggerLeft;
        }
        get touchButtonTriggerRight() {
          return this._touchButtonTriggerRight;
        }
        get touchButtonThumbStickLeft() {
          return this._touchButtonThumbStickLeft;
        }
        get touchButtonThumbStickRight() {
          return this._touchButtonThumbStickRight;
        }
        constructor() {
          this._eventTarget = new EventTarget();
          this._nativeButtonState = {
            [Button$1.BUTTON_SOUTH]: 0,
            [Button$1.BUTTON_EAST]: 0,
            [Button$1.BUTTON_WEST]: 0,
            [Button$1.BUTTON_NORTH]: 0,
            [Button$1.BUTTON_TRIGGER_LEFT]: 0,
            [Button$1.BUTTON_TRIGGER_RIGHT]: 0,
            [Button$1.TRIGGER_LEFT]: 0,
            [Button$1.TRIGGER_RIGHT]: 0,
            [Button$1.GRIP_LEFT]: 0,
            [Button$1.GRIP_RIGHT]: 0,
            [Button$1.LEFT_STICK_UP]: 0,
            [Button$1.LEFT_STICK_DOWN]: 0,
            [Button$1.LEFT_STICK_LEFT]: 0,
            [Button$1.LEFT_STICK_RIGHT]: 0,
            [Button$1.RIGHT_STICK_UP]: 0,
            [Button$1.RIGHT_STICK_DOWN]: 0,
            [Button$1.RIGHT_STICK_LEFT]: 0,
            [Button$1.RIGHT_STICK_RIGHT]: 0,
            [Button$1.BUTTON_LEFT_STICK]: 0,
            [Button$1.BUTTON_RIGHT_STICK]: 0,
            [Button$1.ROKID_MENU]: 0,
            [Button$1.ROKID_START]: 0
          };
          this._nativeTouchState = {
            [StickTouchCode.UNDEFINE]: 0,
            [StickTouchCode.A]: 0,
            [StickTouchCode.B]: 0,
            [StickTouchCode.X]: 0,
            [StickTouchCode.Y]: 0,
            [StickTouchCode.LEFT_TRIGGER]: 0,
            [StickTouchCode.RIGHT_TRIGGER]: 0,
            [StickTouchCode.LEFT_THUMBSTICK]: 0,
            [StickTouchCode.RIGHT_THUMBSTICK]: 0
          };
          this._nativePoseState = {
            [Pose$3.HAND_LEFT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            },
            [Pose$3.HAND_RIGHT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            },
            [Pose$3.AIM_LEFT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            },
            [Pose$3.AIM_RIGHT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            }
          };
          this._initInputSource();
          this._registerEvent();
        }
        _registerEvent() {
          jsb.onHandleInput = infoList => {
            for (let i = 0; i < infoList.length; ++i) {
              const info = infoList[i];
              this._updateNativeButtonState(info);
              this._eventTarget.emit("handle-input", new EventHandle("handle-input", this));
            }
          };
          jsb.onHandlePoseInput = infoList => {
            for (let i = 0; i < infoList.length; ++i) {
              const info = infoList[i];
              this._updateNativePoseState(info);
            }
            this._eventTarget.emit("handle-pose-input", new EventHandle("handle-pose-input", this));
          };
        }
        _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
        _axisToButtons(axisValue) {
          const 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
            };
          }
        }
        _updateNativeButtonState(info) {
          const {
            buttonInfoList,
            axisInfoList,
            touchInfoList
          } = info;
          for (let i = 0; i < buttonInfoList.length; ++i) {
            const buttonInfo = buttonInfoList[i];
            const button = _nativeButtonMap[buttonInfo.code];
            this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0;
          }
          for (let i = 0; i < axisInfoList.length; ++i) {
            const axisInfo = axisInfoList[i];
            const {
              code,
              value
            } = axisInfo;
            let negativeButton;
            let positiveButton;
            let axisValue;
            switch (code) {
              case StickAxisCode.LEFT_STICK_X:
                negativeButton = Button$1.LEFT_STICK_LEFT;
                positiveButton = Button$1.LEFT_STICK_RIGHT;
                axisValue = this._axisToButtons(value);
                break;
              case StickAxisCode.LEFT_STICK_Y:
                negativeButton = Button$1.LEFT_STICK_DOWN;
                positiveButton = Button$1.LEFT_STICK_UP;
                axisValue = this._axisToButtons(value);
                break;
              case StickAxisCode.RIGHT_STICK_X:
                negativeButton = Button$1.RIGHT_STICK_LEFT;
                positiveButton = Button$1.RIGHT_STICK_RIGHT;
                axisValue = this._axisToButtons(value);
                break;
              case StickAxisCode.RIGHT_STICK_Y:
                negativeButton = Button$1.RIGHT_STICK_DOWN;
                positiveButton = Button$1.RIGHT_STICK_UP;
                axisValue = this._axisToButtons(value);
                break;
              case StickAxisCode.L2:
                this._nativeButtonState[Button$1.TRIGGER_LEFT] = value;
                break;
              case StickAxisCode.R2:
                this._nativeButtonState[Button$1.TRIGGER_RIGHT] = value;
                break;
              case StickAxisCode.LEFT_GRIP:
                this._nativeButtonState[Button$1.GRIP_LEFT] = value;
                break;
              case StickAxisCode.RIGHT_GRIP:
                this._nativeButtonState[Button$1.GRIP_RIGHT] = value;
                break;
            }
            if (negativeButton && positiveButton && axisValue) {
              this._nativeButtonState[negativeButton] = axisValue.negative;
              this._nativeButtonState[positiveButton] = axisValue.positive;
            }
          }
          if (touchInfoList) {
            for (let i = 0; i < touchInfoList.length; ++i) {
              const touchInfo = touchInfoList[i];
              const {
                code,
                value
              } = touchInfo;
              switch (code) {
                case StickTouchCode.A:
                case StickTouchCode.B:
                case StickTouchCode.X:
                case StickTouchCode.Y:
                case StickTouchCode.LEFT_TRIGGER:
                case StickTouchCode.RIGHT_TRIGGER:
                case StickTouchCode.LEFT_THUMBSTICK:
                case StickTouchCode.RIGHT_THUMBSTICK:
                  this._nativeTouchState[code] = value;
                  break;
              }
            }
          }
        }
        _updateNativePoseState(info) {
          switch (info.code) {
            case 1:
              this._nativePoseState[Pose$3.HAND_LEFT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
            case 2:
              this._nativePoseState[Pose$3.AIM_LEFT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
            case 4:
              this._nativePoseState[Pose$3.HAND_RIGHT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
            case 5:
              this._nativePoseState[Pose$3.AIM_RIGHT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
          }
        }
        _initInputSource() {
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = () => this._nativeButtonState[Button$1.BUTTON_NORTH];
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = () => this._nativeButtonState[Button$1.BUTTON_EAST];
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = () => this._nativeButtonState[Button$1.BUTTON_WEST];
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = () => this._nativeButtonState[Button$1.BUTTON_SOUTH];
          this._buttonTriggerLeft = new InputSourceButton();
          this._buttonTriggerLeft.getValue = () => this._nativeButtonState[Button$1.BUTTON_TRIGGER_LEFT];
          this._buttonTriggerRight = new InputSourceButton();
          this._buttonTriggerRight.getValue = () => this._nativeButtonState[Button$1.BUTTON_TRIGGER_RIGHT];
          this._triggerLeft = new InputSourceButton();
          this._triggerLeft.getValue = () => this._nativeButtonState[Button$1.TRIGGER_LEFT];
          this._triggerRight = new InputSourceButton();
          this._triggerRight.getValue = () => this._nativeButtonState[Button$1.TRIGGER_RIGHT];
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = () => this._nativeButtonState[Button$1.GRIP_LEFT];
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = () => this._nativeButtonState[Button$1.GRIP_RIGHT];
          this._buttonLeftStick = new InputSourceButton();
          this._buttonLeftStick.getValue = () => this._nativeButtonState[Button$1.BUTTON_LEFT_STICK];
          const leftStickUp = new InputSourceButton();
          leftStickUp.getValue = () => this._nativeButtonState[Button$1.LEFT_STICK_UP];
          const leftStickDown = new InputSourceButton();
          leftStickDown.getValue = () => this._nativeButtonState[Button$1.LEFT_STICK_DOWN];
          const leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = () => this._nativeButtonState[Button$1.LEFT_STICK_LEFT];
          const leftStickRight = new InputSourceButton();
          leftStickRight.getValue = () => this._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 = () => this._nativeButtonState[Button$1.BUTTON_RIGHT_STICK];
          const rightStickUp = new InputSourceButton();
          rightStickUp.getValue = () => this._nativeButtonState[Button$1.RIGHT_STICK_UP];
          const rightStickDown = new InputSourceButton();
          rightStickDown.getValue = () => this._nativeButtonState[Button$1.RIGHT_STICK_DOWN];
          const rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = () => this._nativeButtonState[Button$1.RIGHT_STICK_LEFT];
          const rightStickRight = new InputSourceButton();
          rightStickRight.getValue = () => this._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 = () => this._nativeButtonState[Button$1.ROKID_MENU];
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = () => this._nativeButtonState[Button$1.ROKID_START];
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = () => this._nativePoseState[Pose$3.HAND_LEFT].position;
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = () => this._nativePoseState[Pose$3.HAND_LEFT].orientation;
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = () => this._nativePoseState[Pose$3.HAND_RIGHT].position;
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = () => this._nativePoseState[Pose$3.HAND_RIGHT].orientation;
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = () => this._nativePoseState[Pose$3.AIM_LEFT].position;
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = () => this._nativePoseState[Pose$3.AIM_LEFT].orientation;
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = () => this._nativePoseState[Pose$3.AIM_RIGHT].position;
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = () => this._nativePoseState[Pose$3.AIM_RIGHT].orientation;
          this._touchButtonA = new InputSourceTouch();
          this._touchButtonA.getValue = () => this._nativeTouchState[StickTouchCode.A];
          this._touchButtonB = new InputSourceTouch();
          this._touchButtonB.getValue = () => this._nativeTouchState[StickTouchCode.B];
          this._touchButtonX = new InputSourceTouch();
          this._touchButtonX.getValue = () => this._nativeTouchState[StickTouchCode.X];
          this._touchButtonY = new InputSourceTouch();
          this._touchButtonY.getValue = () => this._nativeTouchState[StickTouchCode.Y];
          this._touchButtonTriggerLeft = new InputSourceTouch();
          this._touchButtonTriggerLeft.getValue = () => this._nativeTouchState[StickTouchCode.LEFT_TRIGGER];
          this._touchButtonTriggerRight = new InputSourceTouch();
          this._touchButtonTriggerRight.getValue = () => this._nativeTouchState[StickTouchCode.RIGHT_TRIGGER];
          this._touchButtonThumbStickLeft = new InputSourceTouch();
          this._touchButtonThumbStickLeft.getValue = () => this._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK];
          this._touchButtonThumbStickRight = new InputSourceTouch();
          this._touchButtonThumbStickRight.getValue = () => this._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK];
        }
      }

      var Pose$2;
      (function (Pose) {
        Pose[Pose["VIEW_LEFT"] = 0] = "VIEW_LEFT";
        Pose[Pose["VIEW_RIGHT"] = 1] = "VIEW_RIGHT";
        Pose[Pose["HEAD_MIDDLE"] = 2] = "HEAD_MIDDLE";
      })(Pose$2 || (Pose$2 = {}));
      class HMDInputDevice {
        get viewLeftPosition() {
          return this._viewLeftPosition;
        }
        get viewLeftOrientation() {
          return this._viewLeftOrientation;
        }
        get viewRightPosition() {
          return this._viewRightPosition;
        }
        get viewRightOrientation() {
          return this._viewRightOrientation;
        }
        get headMiddlePosition() {
          return this._headMiddlePosition;
        }
        get headMiddleOrientation() {
          return this._headMiddleOrientation;
        }
        constructor() {
          this._eventTarget = new EventTarget();
          this._nativePoseState = {
            [Pose$2.VIEW_LEFT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            },
            [Pose$2.VIEW_RIGHT]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            },
            [Pose$2.HEAD_MIDDLE]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            }
          };
          this._initInputSource();
          this._registerEvent();
        }
        _registerEvent() {
          jsb.onHMDPoseInput = infoList => {
            for (let i = 0; i < infoList.length; ++i) {
              const info = infoList[i];
              this._updateNativePoseState(info);
            }
            this._eventTarget.emit("hmd-pose-input", new EventHMD("hmd-pose-input", this));
          };
        }
        _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
        _updateNativePoseState(info) {
          switch (info.code) {
            case 0:
              this._nativePoseState[Pose$2.VIEW_LEFT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
            case 3:
              this._nativePoseState[Pose$2.VIEW_RIGHT] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
            case 6:
              this._nativePoseState[Pose$2.HEAD_MIDDLE] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
          }
        }
        _initInputSource() {
          this._viewLeftPosition = new InputSourcePosition();
          this._viewLeftPosition.getValue = () => this._nativePoseState[Pose$2.VIEW_LEFT].position;
          this._viewLeftOrientation = new InputSourceOrientation();
          this._viewLeftOrientation.getValue = () => this._nativePoseState[Pose$2.VIEW_LEFT].orientation;
          this._viewRightPosition = new InputSourcePosition();
          this._viewRightPosition.getValue = () => this._nativePoseState[Pose$2.VIEW_RIGHT].position;
          this._viewRightOrientation = new InputSourceOrientation();
          this._viewRightOrientation.getValue = () => this._nativePoseState[Pose$2.VIEW_RIGHT].orientation;
          this._headMiddlePosition = new InputSourcePosition();
          this._headMiddlePosition.getValue = () => this._nativePoseState[Pose$2.HEAD_MIDDLE].position;
          this._headMiddleOrientation = new InputSourceOrientation();
          this._headMiddleOrientation.getValue = () => this._nativePoseState[Pose$2.HEAD_MIDDLE].orientation;
        }
      }

      var Pose$1;
      (function (Pose) {
        Pose[Pose["AR_MOBILE"] = 0] = "AR_MOBILE";
      })(Pose$1 || (Pose$1 = {}));
      class HandheldInputDevice {
        get handheldPosition() {
          return this._handheldPosition;
        }
        get handheldOrientation() {
          return this._handheldOrientation;
        }
        constructor() {
          this._eventTarget = new EventTarget();
          this._nativePoseState = {
            [Pose$1.AR_MOBILE]: {
              position: Vec3.ZERO,
              orientation: Quat.IDENTITY
            }
          };
          this._initInputSource();
          this._registerEvent();
        }
        _registerEvent() {
          jsb.onHandheldPoseInput = infoList => {
            for (let i = 0; i < infoList.length; ++i) {
              const info = infoList[i];
              this._updateNativePoseState(info);
            }
            this._eventTarget.emit("handheld-pose-input", new EventHandheld("handheld-pose-input", this));
          };
        }
        _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
        _updateNativePoseState(info) {
          switch (info.code) {
            case 7:
              this._nativePoseState[Pose$1.AR_MOBILE] = {
                position: new Vec3(info.x, info.y, info.z),
                orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW)
              };
              break;
          }
        }
        _initInputSource() {
          this._handheldPosition = new InputSourcePosition();
          this._handheldPosition.getValue = () => this._nativePoseState[Pose$1.AR_MOBILE].position;
          this._handheldOrientation = new InputSourceOrientation();
          this._handheldOrientation.getValue = () => this._nativePoseState[Pose$1.AR_MOBILE].orientation;
        }
      }

      const code2KeyCode = {
        Backspace: 8,
        Tab: 9,
        Enter: 13,
        ShiftLeft: 16,
        ControlLeft: 17,
        AltLeft: 18,
        ShiftRight: 2000,
        ControlRight: 2001,
        AltRight: 2002,
        Pause: 19,
        CapsLock: 20,
        Escape: 27,
        Space: 32,
        PageUp: 33,
        PageDown: 34,
        End: 35,
        Home: 36,
        ArrowLeft: 37,
        ArrowUp: 38,
        ArrowRight: 39,
        ArrowDown: 40,
        Insert: 45,
        Delete: 46,
        Digit0: 48,
        Digit1: 49,
        Digit2: 50,
        Digit3: 51,
        Digit4: 52,
        Digit5: 53,
        Digit6: 54,
        Digit7: 55,
        Digit8: 56,
        Digit9: 57,
        KeyA: 65,
        KeyB: 66,
        KeyC: 67,
        KeyD: 68,
        KeyE: 69,
        KeyF: 70,
        KeyG: 71,
        KeyH: 72,
        KeyI: 73,
        KeyJ: 74,
        KeyK: 75,
        KeyL: 76,
        KeyM: 77,
        KeyN: 78,
        KeyO: 79,
        KeyP: 80,
        KeyQ: 81,
        KeyR: 82,
        KeyS: 83,
        KeyT: 84,
        KeyU: 85,
        KeyV: 86,
        KeyW: 87,
        KeyX: 88,
        KeyY: 89,
        KeyZ: 90,
        Numpad0: 96,
        Numpad1: 97,
        Numpad2: 98,
        Numpad3: 99,
        Numpad4: 100,
        Numpad5: 101,
        Numpad6: 102,
        Numpad7: 103,
        Numpad8: 104,
        Numpad9: 105,
        NumpadMultiply: 106,
        NumpadAdd: 107,
        NumpadSubtract: 109,
        NumpadDecimal: 110,
        NumpadDivide: 111,
        NumpadEnter: 2003,
        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,
        Semicolon: 186,
        Equal: 187,
        Comma: 188,
        Minus: 189,
        Period: 190,
        Slash: 191,
        Backquote: 192,
        BracketLeft: 219,
        Backslash: 220,
        BracketRight: 221,
        Quote: 222
      };

      const nativeKeyCode2KeyCode = {
        12: 144,
        10048: 96,
        10049: 97,
        10050: 98,
        10051: 99,
        10052: 100,
        10053: 101,
        10054: 102,
        10055: 103,
        10056: 104,
        10057: 105,
        20013: 2003,
        20016: 2000,
        20017: 2001,
        20018: 2002
      };
      function getKeyCode(event) {
        if (event.code) {
          if (event.code in code2KeyCode) {
            return code2KeyCode[event.code];
          } else {
            console.error(`Can not find keyCode for code: ${event.code}`);
          }
        }
        return nativeKeyCode2KeyCode[event.keyCode] || event.keyCode;
      }
      class KeyboardInputSource {
        constructor() {
          this._eventTarget = new EventTarget();
          this._keyStateMap = {};
          this._handleKeyboardDown = void 0;
          this._handleKeyboardUp = void 0;
          this._handleKeyboardDown = event => {
            const keyCode = getKeyCode(event);
            if (!this._keyStateMap[keyCode]) {
              const eventKeyDown = this._getInputEvent(event, "keydown");
              this._eventTarget.emit("keydown", eventKeyDown);
            } else {
              const eventKeyPressing = this._getInputEvent(event, "key-pressing");
              this._eventTarget.emit("key-pressing", eventKeyPressing);
            }
            this._keyStateMap[keyCode] = true;
          };
          this._handleKeyboardUp = event => {
            const keyCode = getKeyCode(event);
            const eventKeyUp = this._getInputEvent(event, "keyup");
            this._keyStateMap[keyCode] = false;
            this._eventTarget.emit("keyup", eventKeyUp);
          };
          this._registerEvent();
        }
        dispatchKeyboardDownEvent(nativeKeyboardEvent) {
          this._handleKeyboardDown(nativeKeyboardEvent);
        }
        dispatchKeyboardUpEvent(nativeKeyboardEvent) {
          this._handleKeyboardUp(nativeKeyboardEvent);
        }
        _registerEvent() {
          jsb.onKeyDown = this._handleKeyboardDown;
          jsb.onKeyUp = this._handleKeyboardUp;
        }
        _getInputEvent(event, eventType) {
          const keyCode = getKeyCode(event);
          const eventKeyboard = new EventKeyboard(keyCode, eventType);
          eventKeyboard.windowId = event.windowId;
          return eventKeyboard;
        }
        on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
      }

      class MouseEventElement {
        constructor() {
          this.type = null;
          this.mouseEvent = {
            x: 0,
            y: 0,
            xDelta: 0,
            yDelta: 0,
            button: 0,
            windowId: 0,
            wheelDeltaX: 0,
            wheelDeltaY: 0
          };
        }
      }
      class MouseEventCache {
        constructor() {
          this._events = [];
          this._length = 0;
        }
        push(eventType, mouseEvent) {
          const events = this._events;
          const index = this._length;
          if (index >= events.length) {
            events.push(new MouseEventElement());
          }
          const e = events[index];
          e.type = eventType;
          const cachedEvent = e.mouseEvent;
          if (mouseEvent) {
            Object.assign(cachedEvent, mouseEvent);
          } else {
            cachedEvent.x = cachedEvent.y = cachedEvent.xDelta = cachedEvent.yDelta = 0;
            cachedEvent.button = cachedEvent.windowId = cachedEvent.wheelDeltaX = cachedEvent.wheelDeltaY = 0;
          }
          ++this._length;
        }
        clear() {
          this._length = 0;
        }
        forEach(cb) {
          for (let i = 0, len = this._length; i < len; ++i) {
            cb(this._events[i]);
          }
        }
      }
      class MouseInputSource {
        constructor() {
          this._eventTarget = new EventTarget();
          this._preMousePos = new Vec2();
          this._isPressed = false;
          this._windowManager = void 0;
          this._pointLocked = false;
          this._cache = new MouseEventCache();
          this._handleMouseDown = void 0;
          this._handleMouseMove = void 0;
          this._handleMouseUp = void 0;
          this._handleWindowLeave = void 0;
          this._handleWindowEnter = void 0;
          this._handleMouseWheel = void 0;
          this._handleMouseDown = this._createEventCacheCallback("mouse-down");
          this._handleMouseMove = this._createEventCacheCallback("mouse-move");
          this._handleMouseUp = this._createEventCacheCallback("mouse-up");
          this._handleWindowLeave = this._createEventCacheCallback("mouse-leave-window");
          this._handleWindowEnter = this._createEventCacheCallback("mouse-enter-window");
          this._handleMouseWheel = this._createEventCacheCallback("mouse-wheel");
          this._registerEvent();
          this._windowManager = jsb.ISystemWindowManager.getInstance();
        }
        dispatchMouseDownEvent(nativeMouseEvent) {
          this._handleMouseDown(nativeMouseEvent);
        }
        dispatchMouseMoveEvent(nativeMouseEvent) {
          this._handleMouseMove(nativeMouseEvent);
        }
        dispatchMouseUpEvent(nativeMouseEvent) {
          this._handleMouseUp(nativeMouseEvent);
        }
        dispatchScrollEvent(nativeMouseEvent) {
          this._handleMouseWheel(nativeMouseEvent);
        }
        _getLocation(event) {
          const window = this._windowManager.getWindow(event.windowId);
          const windowSize = window.getViewSize();
          const dpr = screenAdapter.devicePixelRatio;
          const x = event.x * dpr;
          const y = windowSize.height - event.y * dpr;
          return new Vec2(x, y);
        }
        _registerEvent() {
          jsb.onMouseDown = this._handleMouseDown;
          jsb.onMouseMove = this._handleMouseMove;
          jsb.onMouseUp = this._handleMouseUp;
          jsb.onMouseWheel = this._handleMouseWheel;
          jsb.onPointerlockChange = value => {
            this._pointLocked = value;
          };
          jsb.onWindowLeave = this._handleWindowLeave;
          jsb.onWindowEnter = this._handleWindowEnter;
        }
        _createEventCacheCallback(eventType) {
          return mouseEvent => {
            this._cache.push(eventType, mouseEvent);
          };
        }
        dispatchEventsInCache() {
          const cache = this._cache;
          cache.forEach(e => {
            switch (e.type) {
              case "mouse-leave-window":
                this._dispatchWindowLeave();
                break;
              case "mouse-enter-window":
                this._dispatchWindowEnter();
                break;
              case "mouse-wheel":
                this._dispatchMouseWheel(e.mouseEvent);
                break;
              default:
                this._dispatchEvent(e.type, e.mouseEvent);
                break;
            }
          });
          cache.clear();
        }
        _dispatchEvent(eventType, mouseEvent) {
          const location = this._getLocation(mouseEvent);
          let button = mouseEvent.button;
          switch (eventType) {
            case "mouse-down":
              this._isPressed = true;
              break;
            case "mouse-up":
              this._isPressed = false;
              break;
            case "mouse-move":
              if (!this._isPressed) {
                button = EventMouse.BUTTON_MISSING;
              }
              break;
          }
          const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId);
          eventMouse.setLocation(location.x, location.y);
          eventMouse.setButton(button);
          const dpr = screenAdapter.devicePixelRatio;
          eventMouse.movementX = typeof mouseEvent.xDelta === 'undefined' ? 0 : mouseEvent.xDelta * dpr;
          eventMouse.movementY = typeof mouseEvent.yDelta === 'undefined' ? 0 : mouseEvent.yDelta * dpr;
          this._preMousePos.set(location.x, location.y);
          this._eventTarget.emit(eventType, eventMouse);
        }
        _dispatchMouseWheel(mouseEvent) {
          const eventType = "mouse-wheel";
          const location = this._getLocation(mouseEvent);
          const button = mouseEvent.button;
          const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId);
          eventMouse.setLocation(location.x, location.y);
          eventMouse.setButton(button);
          eventMouse.movementX = location.x - this._preMousePos.x;
          eventMouse.movementY = this._preMousePos.y - location.y;
          const matchStandardFactor = 120;
          eventMouse.setScrollData(mouseEvent.wheelDeltaX * matchStandardFactor, mouseEvent.wheelDeltaY * matchStandardFactor);
          this._preMousePos.set(location.x, location.y);
          this._eventTarget.emit(eventType, eventMouse);
        }
        on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
        _dispatchWindowLeave() {
          const eventType = "mouse-leave-window";
          const eventMouse = new EventMouse(eventType, false);
          this._eventTarget.emit(eventType, eventMouse);
        }
        _dispatchWindowEnter() {
          const eventType = "mouse-enter-window";
          const eventMouse = new EventMouse(eventType, false);
          this._eventTarget.emit(eventType, eventMouse);
        }
      }

      const tempVec2$1 = new Vec2();
      class TouchManager {
        constructor() {
          this._touchMap = new Map();
          this._maxTouches = 8;
        }
        _createTouch(touchID, x, y) {
          if (this._touchMap.has(touchID)) {
            logID(2301);
            return undefined;
          }
          const checkResult = this._checkTouchMapSizeMoreThanMax(touchID);
          if (checkResult) {
            logID(2300);
            return undefined;
          }
          const touch = new Touch(x, y, touchID);
          this._touchMap.set(touchID, touch);
          this._updateTouch(touch, x, y);
          return touch;
        }
        releaseTouch(touchID) {
          if (!this._touchMap.has(touchID)) {
            return;
          }
          this._touchMap.delete(touchID);
        }
        getTouch(touchID) {
          return this._touchMap.get(touchID);
        }
        getOrCreateTouch(touchID, x, y) {
          let touch = this.getTouch(touchID);
          if (!touch) {
            touch = this._createTouch(touchID, x, y);
          } else {
            this._updateTouch(touch, x, y);
          }
          return touch;
        }
        getAllTouches() {
          const touches = [];
          this._touchMap.forEach(touch => {
            if (touch) {
              touches.push(touch);
            }
          });
          return touches;
        }
        getTouchCount() {
          return this._touchMap.size;
        }
        _updateTouch(touch, x, y) {
          touch.getLocation(tempVec2$1);
          touch.setPrevPoint(tempVec2$1);
          touch.setPoint(x, y);
        }
        _checkTouchMapSizeMoreThanMax(touchID) {
          if (this._touchMap.has(touchID)) {
            return false;
          }
          const maxSize = macro.ENABLE_MULTI_TOUCH ? this._maxTouches : 1;
          if (this._touchMap.size < maxSize) {
            return false;
          }
          const now = performance.now();
          this._touchMap.forEach(touch => {
            if (now - touch.lastModified > macro.TOUCH_TIMEOUT) {
              logID(2302, touch.getID());
              this.releaseTouch(touch.getID());
            }
          });
          return maxSize >= this._touchMap.size;
        }
      }
      const touchManager = new TouchManager();

      class TouchEventElement {
        constructor() {
          this.type = null;
          this.changedTouches = [];
          this.windowId = 0;
        }
      }
      class TouchEventCache {
        constructor() {
          this._events = [];
          this._length = 0;
        }
        push(eventType, changedTouches, windowId) {
          const events = this._events;
          const index = this._length;
          if (index >= events.length) {
            events.push(new TouchEventElement());
          }
          const e = events[index];
          const cachedTouches = e.changedTouches;
          e.type = eventType;
          cachedTouches.length = changedTouches.length;
          e.windowId = windowId;
          for (let i = 0, len = changedTouches.length; i < len; ++i) {
            const src = changedTouches[i];
            let dst = cachedTouches[i];
            if (!dst) {
              cachedTouches[i] = dst = {};
            }
            Object.assign(dst, src);
          }
          ++this._length;
        }
        clear() {
          this._length = 0;
        }
        forEach(cb) {
          for (let i = 0, len = this._length; i < len; ++i) {
            cb(this._events[i]);
          }
        }
      }
      class TouchInputSource {
        constructor() {
          this._eventTarget = new EventTarget();
          this._windowManager = void 0;
          this._cache = new TouchEventCache();
          this._registerEvent();
          this._windowManager = jsb.ISystemWindowManager.getInstance();
        }
        _registerEvent() {
          jsb.onTouchStart = this._createEventCacheCallback("touch-start");
          jsb.onTouchMove = this._createEventCacheCallback("touch-move");
          jsb.onTouchEnd = this._createEventCacheCallback("touch-end");
          jsb.onTouchCancel = this._createEventCacheCallback("touch-cancel");
        }
        _createEventCacheCallback(eventType) {
          return (changedTouches, windowId) => {
            this._cache.push(eventType, changedTouches, windowId);
          };
        }
        dispatchEventsInCache() {
          const cache = this._cache;
          cache.forEach(e => {
            this._dispatchEvent(e.type, e.changedTouches, e.windowId);
          });
          cache.clear();
        }
        _dispatchEvent(eventType, changedTouches, windowId) {
          const handleTouches = [];
          const length = changedTouches.length;
          const windowSize = this._windowManager.getWindow(windowId).getViewSize();
          for (let i = 0; i < length; ++i) {
            const changedTouch = changedTouches[i];
            const touchID = changedTouch.identifier;
            if (touchID === null) {
              continue;
            }
            const location = this._getLocation(changedTouch, windowSize);
            const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y);
            if (!touch) {
              continue;
            }
            if (eventType === "touch-end" || eventType === "touch-cancel") {
              touchManager.releaseTouch(touchID);
            }
            handleTouches.push(touch);
          }
          if (handleTouches.length > 0) {
            const eventTouch = new EventTouch(handleTouches, false, eventType, touchManager.getAllTouches());
            eventTouch.windowId = windowId;
            this._eventTarget.emit(eventType, eventTouch);
          }
        }
        _getLocation(touch, windowSize) {
          const dpr = screenAdapter.devicePixelRatio;
          const x = touch.clientX * dpr;
          const y = windowSize.height - touch.clientY * dpr;
          return new Vec2(x, y);
        }
        on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        }
      }

      class InputEventDispatcher {
        constructor(inputEventTarget) {
          this.priority = 0;
          this._inputEventTarget = inputEventTarget;
        }
        onThrowException() {}
        dispatchEvent(event) {
          this._inputEventTarget.emit(event.type, event);
          return true;
        }
      }
      const pointerEventTypeMap = {
        ["mouse-down"]: "touch-start",
        ["mouse-move"]: "touch-move",
        ["mouse-up"]: "touch-end"
      };
      class Input {
        constructor() {
          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._eventKeyboardList = [];
          this._eventAccelerationList = [];
          this._eventGamepadList = [];
          this._eventHandleList = [];
          this._eventHMDList = [];
          this._eventHandheldList = [];
          this._needSimulateTouchMoveEvent = false;
          this._eventDispatcherList = [];
          this._registerEvent();
          this._inputEventDispatcher = new InputEventDispatcher(this._eventTarget);
          this._registerEventDispatcher(this._inputEventDispatcher);
          GamepadInputDevice._init();
        }
        _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);
        }
        _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);
        }
        _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);
        }
        _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);
        }
        _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);
        }
        _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);
        }
        on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
          return callback;
        }
        once(eventType, callback, target) {
          this._eventTarget.once(eventType, callback, target);
          return callback;
        }
        off(eventType, callback, target) {
          this._eventTarget.off(eventType, callback, target);
        }
        getTouch(touchID) {
          return touchManager.getTouch(touchID);
        }
        getAllTouches() {
          return touchManager.getAllTouches();
        }
        getTouchCount() {
          return touchManager.getTouchCount();
        }
        setAccelerometerEnabled(isEnable) {
          if (isEnable) {
            this._accelerometerInput.start();
          } else {
            this._accelerometerInput.stop();
          }
        }
        setAccelerometerInterval(intervalInMileSeconds) {
          this._accelerometerInput.setInterval(intervalInMileSeconds);
        }
        _simulateEventTouch(eventMouse) {
          const eventType = pointerEventTypeMap[eventMouse.type];
          const touchID = 0;
          const touch = touchManager.getOrCreateTouch(touchID, eventMouse.getLocationX(), eventMouse.getLocationY());
          if (!touch) {
            return;
          }
          const changedTouches = [touch];
          const eventTouch = new EventTouch(changedTouches, false, eventType, eventType === "touch-end" ? [] : changedTouches);
          eventTouch.windowId = eventMouse.windowId;
          if (eventType === "touch-end") {
            touchManager.releaseTouch(touchID);
          }
          this._dispatchEventTouch(eventTouch);
        }
        _registerEventDispatcher(eventDispatcher) {
          this._eventDispatcherList.push(eventDispatcher);
          this._eventDispatcherList.sort((a, b) => b.priority - a.priority);
        }
        _emitEvent(event) {
          const length = this._eventDispatcherList.length;
          for (let i = 0; i < length; ++i) {
            const dispatcher = this._eventDispatcherList[i];
            try {
              if (!dispatcher.dispatchEvent(event)) {
                break;
              }
            } catch (e) {
              this._clearEvents();
              dispatcher.onThrowException();
              throw e;
            }
          }
        }
        _registerEvent() {
          if (sys.hasFeature(sys.Feature.INPUT_TOUCH)) {
            this._touchInput.on("touch-start", event => {
              this._dispatchEventTouch(event);
            });
            this._touchInput.on("touch-move", event => {
              this._dispatchEventTouch(event);
            });
            this._touchInput.on("touch-end", event => {
              this._dispatchEventTouch(event);
            });
            this._touchInput.on("touch-cancel", event => {
              this._dispatchEventTouch(event);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
            this._mouseInput.on("mouse-down", event => {
              this._needSimulateTouchMoveEvent = true;
              this._simulateEventTouch(event);
              this._dispatchEventMouse(event);
            });
            this._mouseInput.on("mouse-move", event => {
              if (this._needSimulateTouchMoveEvent) {
                this._simulateEventTouch(event);
              }
              this._dispatchEventMouse(event);
            });
            this._mouseInput.on("mouse-up", event => {
              this._needSimulateTouchMoveEvent = false;
              this._simulateEventTouch(event);
              this._dispatchEventMouse(event);
            });
            this._mouseInput.on("mouse-wheel", event => {
              this._dispatchEventMouse(event);
            });
            this._mouseInput.on("mouse-leave-window", event => {
              this._dispatchEventMouse(event);
            });
            this._mouseInput.on("mouse-enter-window", event => {
              this._dispatchEventMouse(event);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_KEYBOARD)) {
            const eventKeyboardList = this._eventKeyboardList;
            this._keyboardInput.on("keydown", event => {
              this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on("key-pressing", event => {
              this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on("keyup", event => {
              this._dispatchOrPushEvent(event, eventKeyboardList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_ACCELEROMETER)) {
            const eventAccelerationList = this._eventAccelerationList;
            this._accelerometerInput.on("devicemotion", event => {
              this._dispatchOrPushEvent(event, eventAccelerationList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) {
            const eventGamepadList = this._eventGamepadList;
            GamepadInputDevice._on("gamepad-change", event => {
              this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on("gamepad-input", event => {
              this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on("handle-pose-input", event => {
              this._dispatchOrPushEvent(event, eventGamepadList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) {
            const eventHandleList = this._eventHandleList;
            this._handleInput._on("handle-input", event => {
              this._dispatchOrPushEvent(event, eventHandleList);
            });
            this._handleInput._on("handle-pose-input", event => {
              this._dispatchOrPushEvent(event, eventHandleList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HMD)) {
            const eventHMDList = this._eventHMDList;
            this._hmdInput._on("hmd-pose-input", event => {
              this._dispatchOrPushEvent(event, eventHMDList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDHELD)) {
            const eventHandheldList = this._eventHandheldList;
            this._handheldInput._on("handheld-pose-input", event => {
              this._dispatchOrPushEvent(event, eventHandheldList);
            });
          }
        }
        _clearEvents() {
          this._eventKeyboardList.length = 0;
          this._eventAccelerationList.length = 0;
          this._eventGamepadList.length = 0;
          this._eventHandleList.length = 0;
          this._eventHMDList.length = 0;
        }
        _dispatchOrPushEvent(event, eventList) {
          {
            eventList.push(event);
          }
        }
        _dispatchEventMouse(event) {
          this._emitEvent(event);
        }
        _dispatchEventTouch(eventTouch) {
          const touches = eventTouch.getTouches();
          const touchesLength = touches.length;
          for (let i = 0; i < touchesLength; ++i) {
            eventTouch.touch = touches[i];
            eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false;
            this._emitEvent(eventTouch);
          }
        }
        _frameDispatchEvents() {
          const eventHMDList = this._eventHMDList;
          for (let i = 0, length = eventHMDList.length; i < length; ++i) {
            const eventHMD = eventHMDList[i];
            this._emitEvent(eventHMD);
          }
          const eventHandheldList = this._eventHandheldList;
          for (let i = 0, length = eventHandheldList.length; i < length; ++i) {
            const eventHandheld = eventHandheldList[i];
            this._emitEvent(eventHandheld);
          }
          this._mouseInput.dispatchEventsInCache();
          this._touchInput.dispatchEventsInCache();
          const eventKeyboardList = this._eventKeyboardList;
          for (let i = 0, length = eventKeyboardList.length; i < length; ++i) {
            const eventKeyboard = eventKeyboardList[i];
            this._emitEvent(eventKeyboard);
          }
          const eventAccelerationList = this._eventAccelerationList;
          for (let i = 0, length = eventAccelerationList.length; i < length; ++i) {
            const eventAcceleration = eventAccelerationList[i];
            this._emitEvent(eventAcceleration);
          }
          const eventGamepadList = this._eventGamepadList;
          for (let i = 0, length = eventGamepadList.length; i < length; ++i) {
            const eventGamepad = eventGamepadList[i];
            this._emitEvent(eventGamepad);
          }
          const eventHandleList = this._eventHandleList;
          for (let i = 0, length = eventHandleList.length; i < length; ++i) {
            const eventHandle = eventHandleList[i];
            this._emitEvent(eventHandle);
          }
          this._clearEvents();
        }
      } exports("Input", Input);
      Input.EventType = InputEventType;
      const input$1 = exports("input", new Input());

      class SystemEvent extends EventTarget {
        constructor() {
          super();
          input$1.on("mouse-down", e => {
            this.emit("mouse-down", e);
          });
          input$1.on("mouse-move", e => {
            this.emit("mouse-move", e);
          });
          input$1.on("mouse-up", e => {
            this.emit("mouse-up", e);
          });
          input$1.on("mouse-wheel", e => {
            this.emit("mouse-wheel", e);
          });
          input$1.on("touch-start", e => {
            this.emit("touch-start", e.touch, e);
          });
          input$1.on("touch-move", e => {
            this.emit("touch-move", e.touch, e);
          });
          input$1.on("touch-end", e => {
            this.emit("touch-end", e.touch, e);
          });
          input$1.on("touch-cancel", e => {
            this.emit("touch-cancel", e.touch, e);
          });
          input$1.on("keydown", e => {
            this.emit("keydown", e);
          });
          input$1.on("key-pressing", e => {
            this.emit("keydown", e);
          });
          input$1.on("keyup", e => {
            this.emit("keyup", e);
          });
          input$1.on("devicemotion", e => {
            this.emit("devicemotion", e);
          });
        }
        setAccelerometerEnabled(isEnabled) {
          input$1.setAccelerometerEnabled(isEnabled);
        }
        setAccelerometerInterval(interval) {
          input$1.setAccelerometerInterval(interval);
        }
        on(type, callback, target, once) {
          super.on(type, callback, target, once);
          return callback;
        }
        off(type, callback, target) {
          super.off(type, callback, target);
        }
      } exports("SystemEvent", SystemEvent);
      SystemEvent.EventType = SystemEventType;
      cclegacy.SystemEvent = SystemEvent;
      const systemEvent = exports("systemEvent", new SystemEvent());
      cclegacy.systemEvent = systemEvent;

      replaceProperty(SystemEventType, 'Node.EventType', [{
        name: 'POSITION_PART',
        newName: 'TRANSFORM_CHANGED'
      }, {
        name: 'ROTATION_PART',
        newName: 'TRANSFORM_CHANGED'
      }, {
        name: 'SCALE_PART',
        newName: 'TRANSFORM_CHANGED'
      }]);
      replaceProperty(Event, 'Event', [{
        name: 'ACCELERATION',
        newName: 'DEVICEMOTION',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(Event, 'Event', [{
        name: 'TOUCH',
        suggest: 'please use SystemEvent.EventType.TOUCH_START, SystemEvent.EventType.TOUCH_MOVE, SystemEvent.EventType.TOUCH_END and SystemEvent.EventType.TOUCH_CANCEL instead'
      }, {
        name: 'MOUSE',
        suggest: 'please use SystemEvent.EventType.MOUSE_DOWN, SystemEvent.EventType.MOUSE_MOVE, SystemEvent.EventType.MOUSE_UP, SystemEvent.EventType.MOUSE_WHEEL, Node.EventType.MOUSE_ENTER and Node.EventType.MOUSE_LEAVE instead'
      }, {
        name: 'KEYBOARD',
        suggest: 'please use SystemEvent.EventType.KEY_DOWN and SystemEvent.EventType.KEY_UP instead'
      }]);
      replaceProperty(EventMouse, 'EventMouse', ['DOWN', 'UP', 'MOVE'].map(item => ({
        name: item,
        newName: `MOUSE_${item}`,
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      })));
      replaceProperty(EventMouse, 'EventMouse', [{
        name: 'SCROLL',
        newName: 'MOUSE_WHEEL',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(EventMouse.prototype, 'EventMouse.prototype', [{
        name: 'eventType',
        suggest: 'please use EventMouse.prototype.type instead'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'BEGAN',
        newName: 'TOUCH_START',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'MOVED',
        newName: 'TOUCH_MOVE',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'ENDED',
        newName: 'TOUCH_END',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'CANCELLED',
        newName: 'TOUCH_CANCEL',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(EventTouch.prototype, 'EventTouch.prototype', [{
        name: 'getEventCode',
        suggest: 'please use EventTouch.prototype.type instead'
      }]);
      replaceProperty(EventTouch.prototype, 'EventTouch.prototype', [{
        name: 'getUILocationInView',
        newName: 'getLocationInView',
        target: EventTouch,
        targetName: 'EventTouch'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', ['back', 'menu', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '*', '+', '-', '/', ';', '=', ',', '.', '[', ']', 'dpadLeft', 'dpadRight', 'dpadUp', 'dpadDown', 'dpadCenter'].map(item => ({
        name: item
      })));
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'shift',
        suggest: 'please use 16 instead'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'ctrl',
        suggest: 'please use 17 instead'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'alt',
        suggest: 'please use 18 instead'
      }]);
      markAsWarning(macro, 'macro', [{
        name: 'KEY',
        suggest: 'please use KeyCode instead'
      }]);

      const PipelineEventType = exports("PipelineEventType", {
        "RENDER_FRAME_BEGIN": "render-frame-begin",
        "RENDER_FRAME_END": "render-frame-end",
        "RENDER_CAMERA_BEGIN": "render-camera-begin",
        "RENDER_CAMERA_END": "render-camera-end",
        "ATTACHMENT_SCALE_CAHNGED": "attachment-scale-changed"
      });
      class PipelineEventProcessor extends EventTarget {
        constructor() {
          super();
          this.eventTargetOn = super.on;
          this.eventTargetOnce = super.once;
        }
        on(type, callback, target, once) {
          return this.eventTargetOn(type, callback, target, once);
        }
        once(type, callback, target) {
          return this.eventTargetOnce(type, callback, target);
        }
      }

      const Root = exports("Root", jsb.Root);
      var LightType$1;
      (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$1 || (LightType$1 = {}));
      const rootProto = Root.prototype;
      rootProto._createBatcher2D = function () {
        if (!this._batcher && legacyCC.internal.Batcher2D) {
          this._batcher = new legacyCC.internal.Batcher2D(this);
          if (!this._batcher.initialize()) {
            this._batcher = null;
            this.destroy();
            return;
          }
          this._batcher._nativeObj = this.getBatcher2D();
        }
      };
      Object.defineProperty(rootProto, 'batcher2D', {
        configurable: true,
        enumerable: true,
        get() {
          return this._batcher;
        }
      });
      Object.defineProperty(rootProto, 'dataPoolManager', {
        configurable: true,
        enumerable: true,
        get() {
          return this._dataPoolMgr;
        }
      });
      Object.defineProperty(rootProto, 'pipelineEvent', {
        configurable: true,
        enumerable: true,
        get() {
          return this._pipelineEvent;
        }
      });
      rootProto._ctor = function (device) {
        this._device = device;
        this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device);
        this._modelPools = new Map();
        this._lightPools = new Map();
        this._batcher = null;
        this._pipelineEvent = new PipelineEventProcessor();
        this._registerListeners();
      };
      rootProto.initialize = function (info) {
        var _this$_dataPoolMgr;
        this._initialize(deviceManager.swapchain);
        const customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || [];
        (_this$_dataPoolMgr = this._dataPoolMgr) === null || _this$_dataPoolMgr === void 0 ? void 0 : _this$_dataPoolMgr.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts);
      };
      rootProto.createModel = function (ModelCtor) {
        let p = this._modelPools.get(ModelCtor);
        if (!p) {
          this._modelPools.set(ModelCtor, new Pool(() => new ModelCtor(), 10, obj => obj.destroy()));
          p = this._modelPools.get(ModelCtor);
        }
        const model = p.alloc();
        model.initialize();
        return model;
      };
      rootProto.destroyModel = function (m) {
        const 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();
      };
      rootProto.createLight = function (LightCtor) {
        let l = this._lightPools.get(LightCtor);
        if (!l) {
          this._lightPools.set(LightCtor, new Pool(() => new LightCtor(), 4, obj => obj.destroy()));
          l = this._lightPools.get(LightCtor);
        }
        const light = l.alloc();
        light.initialize();
        return light;
      };
      rootProto.destroyLight = function (l) {
        if (l.scene) {
          switch (l.type) {
            case 0:
              l.scene.removeDirectionalLight(l);
              break;
            case 1:
              l.scene.removeSphereLight(l);
              break;
            case 2:
              l.scene.removeSpotLight(l);
              break;
            case 3:
              l.scene.removePointLight(l);
              break;
            case 4:
              l.scene.removeRangedDirLight(l);
              break;
          }
        }
        l.destroy();
      };
      rootProto.recycleLight = function (l) {
        const p = this._lightPools.get(l.constructor);
        if (p) {
          p.free(l);
          if (l.scene) {
            switch (l.type) {
              case 0:
                l.scene.removeDirectionalLight(l);
                break;
              case 1:
                l.scene.removeSphereLight(l);
                break;
              case 2:
                l.scene.removeSpotLight(l);
                break;
              case 3:
                l.scene.removePointLight(l);
                break;
              case 4:
                l.scene.removeRangedDirLight(l);
                break;
            }
          }
        }
      };
      rootProto._onDirectorBeforeCommit = function () {
        legacyCC.director.emit(legacyCC.Director.EVENT_BEFORE_COMMIT);
      };
      rootProto._onDirectorBeforeRender = function () {
        legacyCC.director.emit(legacyCC.Director.EVENT_BEFORE_RENDER);
      };
      rootProto._onDirectorAfterRender = function () {
        legacyCC.director.emit(legacyCC.Director.EVENT_AFTER_RENDER);
      };
      rootProto._onDirectorPipelineChanged = function () {
        const scene = legacyCC.director.getScene();
        if (scene) {
          scene._activate();
        }
      };
      const oldOnGlobalPipelineStateChanged = rootProto.onGlobalPipelineStateChanged;
      rootProto.onGlobalPipelineStateChanged = function () {
        oldOnGlobalPipelineStateChanged.call(this);
        const builder = legacyCC.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME);
        if (builder) {
          if (typeof builder.onGlobalPipelineStateChanged === 'function') {
            builder.onGlobalPipelineStateChanged();
          }
          legacyCC.rendering.forceResizeAllWindows();
        }
      };
      const oldFrameMove = rootProto.frameMove;
      rootProto.frameMove = function (deltaTime) {
        oldFrameMove.call(this, deltaTime, legacyCC.director.getTotalFrames());
      };
      const oldSetPipeline = rootProto.setRenderPipeline;
      rootProto.setRenderPipeline = function (customPipeline) {
        let ppl;
        if (customPipeline) {
          legacyCC.rendering.createCustomPipeline();
          ppl = oldSetPipeline.call(this, null);
          log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
        } else {
          if (cclegacy.legacy_rendering) {
            const pipeline = cclegacy.legacy_rendering.createDefaultPipeline();
            pipeline.init();
            ppl = oldSetPipeline.call(this, pipeline);
          } else {
            log(`No render pipeline: legacy-pipeline is not available`);
          }
        }
        this._createBatcher2D();
        return ppl;
      };
      rootProto.addBatch = function (batch) {
        console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.');
      };
      rootProto.removeBatch = function (batch) {
        console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.');
      };
      rootProto.removeBatches = function () {
        console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.');
      };

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

      class NodeUIProperties {
        get uiTransformComp() {
          if (!this._uiTransformComp) {
            this._uiTransformComp = this._node.getComponent('cc.UITransform');
          }
          return this._uiTransformComp;
        }
        set uiTransformComp(value) {
          this._uiTransformComp = value;
        }
        get uiComp() {
          return this._uiComp;
        }
        set uiComp(comp) {
          if (this._uiComp && comp) {
            warnID(12002);
            return;
          }
          this._uiComp = comp;
        }
        setOpacity(v) {
          this._opacity = v;
        }
        get opacity() {
          return this._opacity;
        }
        get localOpacity() {
          return this._localOpacity;
        }
        set localOpacity(val) {
          this._localOpacity = val;
          this.colorDirty = true;
        }
        constructor(node) {
          this._uiComp = null;
          this._opacity = 1;
          this._localOpacity = 1;
          this.colorDirty = true;
          this._uiTransformComp = null;
          this._node = node;
        }
        applyOpacity(effectOpacity) {
          this._opacity = this._localOpacity * effectOpacity;
        }
        static markOpacityTree(node, isDirty = true) {}
      }

      const NodeSpace = exports("NodeSpace", {
        "LOCAL": 0,
        "WORLD": 1
      });
      const TransformBit = exports("TransformBit", {
        "NONE": 0,
        "POSITION": 1,
        "ROTATION": 2,
        "SCALE": 4,
        "RS": 6,
        "TRS": 7,
        "TRS_MASK": -8
      });
      legacyCC.internal.TransformBit = TransformBit;
      const MobilityMode = exports("MobilityMode", Enum({
        Static: 0,
        Stationary: 1,
        Movable: 2
      }));

      const 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
      };
      class Layers {
        static init() {
          const userLayers = settings.querySettings("engine", 'customLayers');
          if (!userLayers) return;
          for (let i = 0; i < userLayers.length; i++) {
            const layer = userLayers[i];
            Layers.addLayer(layer.name, layer.bit);
          }
        }
        static makeMaskInclude(includes) {
          let mask = 0;
          for (const inc of includes) {
            mask |= inc;
          }
          return mask;
        }
        static makeMaskExclude(excludes) {
          return ~Layers.makeMaskInclude(excludes);
        }
        static addLayer(name, bitNum) {
          if (bitNum === undefined) {
            warnID(16364);
            return;
          }
          if (bitNum > 19 || bitNum < 0) {
            warnID(16365);
            return;
          }
          const 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);
        }
        static deleteLayer(bitNum) {
          if (bitNum > 19 || bitNum < 0) {
            warnID(16366);
            return;
          }
          const 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);
        }
        static nameToLayer(name) {
          if (name === undefined) {
            warnID(16367);
            return -1;
          }
          return log2(Layers.Enum[name]);
        }
        static layerToName(bitNum) {
          if (bitNum > 31 || bitNum < 0) {
            warnID(16368);
            return '';
          }
          return Layers.Enum[1 << bitNum];
        }
      } exports("Layers", Layers);
      Layers.Enum = Enum(layerList);
      Layers.BitMask = BitMask({
        ...layerList
      });
      legacyCC.Layers = Layers;

      const _tempFloatArray = new Float32Array(jsb.createExternalArrayBuffer(20 * 4));
      const fillMat4WithTempFloatArray = function fillMat4WithTempFloatArray(out) {
        Mat4.set(out, _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3], _tempFloatArray[4], _tempFloatArray[5], _tempFloatArray[6], _tempFloatArray[7], _tempFloatArray[8], _tempFloatArray[9], _tempFloatArray[10], _tempFloatArray[11], _tempFloatArray[12], _tempFloatArray[13], _tempFloatArray[14], _tempFloatArray[15]);
      };

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

      const reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab');
      const Node$1 = jsb.Node; exports({ Node: Node$1, BaseNode: Node$1 });
      legacyCC.Node = Node$1;
      const NodeCls = Node$1;
      NodeCls.reserveContentsForAllSyncablePrefabTag = reserveContentsForAllSyncablePrefabTag;
      NodeCls.EventType = NodeEventType;
      NodeCls.NodeSpace = NodeSpace;
      NodeCls.TransformDirtyBit = TransformBit;
      NodeCls.TransformBit = TransformBit;
      const TRANSFORMBIT_TRS = 7;
      const nodeProto = jsb.Node.prototype;
      const TRANSFORM_ON = 1 << 0;
      const ACTIVE_ON = 1 << 1;
      const Destroying = CCObject.Flags.Destroying;
      Node$1._setTempFloatArray(_tempFloatArray.buffer);
      function getConstructor(typeOrClassName) {
        if (!typeOrClassName) {
          return null;
        }
        if (typeof typeOrClassName === 'string') {
          return getClassByName(typeOrClassName);
        }
        return typeOrClassName;
      }
      nodeProto.attr = function (attrs) {
        mixin(this, attrs);
      };
      nodeProto.getComponent = function (typeOrClassName) {
        const constructor = getConstructor(typeOrClassName);
        if (constructor) {
          return NodeCls._findComponent(this, constructor);
        }
        return null;
      };
      nodeProto.getComponents = function (typeOrClassName) {
        const constructor = getConstructor(typeOrClassName);
        const components = [];
        if (constructor) {
          NodeCls._findComponents(this, constructor, components);
        }
        return components;
      };
      nodeProto.getComponentInChildren = function (typeOrClassName) {
        const constructor = getConstructor(typeOrClassName);
        if (constructor) {
          return NodeCls._findChildComponent(this._children, constructor);
        }
        return null;
      };
      nodeProto.getComponentsInChildren = function (typeOrClassName) {
        const constructor = getConstructor(typeOrClassName);
        const components = [];
        if (constructor) {
          NodeCls._findComponents(this, constructor, components);
          NodeCls._findChildComponents(this.children, constructor, components);
        }
        return components;
      };
      nodeProto.addComponent = function (typeOrClassName) {
        let 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, Component)) {
          throw TypeError(getError(3810));
        }
        const reqComps = constructor._requireComponent;
        if (reqComps) {
          const tryAdd = c => {
            if (!this.getComponent(c)) {
              this.addComponent(c);
            }
          };
          if (Array.isArray(reqComps)) {
            reqComps.forEach(c => tryAdd(c));
          } else {
            tryAdd(reqComps);
          }
        }
        const component = new constructor();
        component.node = this;
        this._components.push(component);
        this.emit("component-added", component);
        if (this._activeInHierarchy) {
          legacyCC.director._nodeActivator.activateComp(component);
        }
        return component;
      };
      nodeProto.removeComponent = function (component) {
        if (!component) {
          errorID(3813);
          return;
        }
        let componentInstance = null;
        if (component instanceof Component) {
          componentInstance = component;
        } else {
          componentInstance = this.getComponent(component);
        }
        if (componentInstance) {
          componentInstance.destroy();
        }
      };
      const REGISTERED_EVENT_MASK_TRANSFORM_CHANGED = 1 << 0;
      const REGISTERED_EVENT_MASK_PARENT_CHANGED = 1 << 1;
      const REGISTERED_EVENT_MASK_MOBILITY_CHANGED = 1 << 2;
      const REGISTERED_EVENT_MASK_LAYER_CHANGED = 1 << 3;
      const REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED = 1 << 4;
      const REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED = 1 << 5;
      nodeProto.on = function (type, callback, target, useCapture = false) {
        switch (type) {
          case "transform-changed":
            this._eventMask |= TRANSFORM_ON;
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_TRANSFORM_CHANGED)) {
              this._registerOnTransformChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_TRANSFORM_CHANGED;
            }
            break;
          case "active-changed":
            this._eventMask |= ACTIVE_ON;
            break;
          case "parent-changed":
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_PARENT_CHANGED)) {
              this._registerOnParentChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_PARENT_CHANGED;
            }
            break;
          case "mobility-changed":
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_MOBILITY_CHANGED)) {
              this._registerOnMobilityChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_MOBILITY_CHANGED;
            }
            break;
          case "layer-changed":
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_LAYER_CHANGED)) {
              this._registerOnLayerChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_LAYER_CHANGED;
            }
            break;
          case "sibling-order-changed":
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED)) {
              this._registerOnSiblingOrderChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED;
            }
            break;
          case "light-probe-baking-changed":
            if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED)) {
              this._registerOnLightProbeBakingChanged();
              this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_LIGHT_PROBE_BAKING_CHANGED;
            }
            break;
        }
        this._eventProcessor.on(type, callback, target, useCapture);
      };
      nodeProto.off = function (type, callback, target, useCapture = false) {
        this._eventProcessor.off(type, callback, target, useCapture);
        const hasListeners = this._eventProcessor.hasEventListener(type);
        if (!hasListeners) {
          switch (type) {
            case "transform-changed":
              this._eventMask &= ~TRANSFORM_ON;
              break;
            case "active-changed":
              this._eventMask &= ~ACTIVE_ON;
              break;
          }
        }
      };
      nodeProto.once = function (type, callback, target, useCapture) {
        this._eventProcessor.once(type, callback, target, useCapture);
      };
      nodeProto.emit = function (type, arg0, arg1, arg2, arg3, arg4) {
        this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
      };
      nodeProto.dispatchEvent = function (event) {
        this._eventProcessor.dispatchEvent(event);
      };
      nodeProto.hasEventListener = function (type, callback, target) {
        return this._eventProcessor.hasEventListener(type, callback, target);
      };
      nodeProto.targetOff = function (target) {
        this._eventProcessor.targetOff(target);
        if (this._eventMask & TRANSFORM_ON && !this._eventProcessor.hasEventListener("transform-changed")) {
          this._eventMask &= ~TRANSFORM_ON;
        }
        if (this._eventMask & ACTIVE_ON && !this._eventProcessor.hasEventListener("active-changed")) {
          this._eventMask &= ~ACTIVE_ON;
        }
      };
      nodeProto.pauseSystemEvents = function pauseSystemEvents(recursive) {
        this._eventProcessor.setEnabled(false, recursive);
      };
      nodeProto.resumeSystemEvents = function resumeSystemEvents(recursive) {
        this._eventProcessor.setEnabled(true, recursive);
      };
      nodeProto.getWritableComponents = function () {
        return this._components;
      };
      nodeProto._setActiveInHierarchy = function (v) {
        return this._activeInHierarchy = v;
      };
      nodeProto._removeComponent = function (component) {
        if (!component) {
          errorID(3814);
          return;
        }
        if (!(this._objFlags & Destroying)) {
          const i = this._components.indexOf(component);
          if (i !== -1) {
            this._components.splice(i, 1);
            this.emit("component-removed", component);
          } else if (component.node !== this) {
            errorID(3815);
          }
        }
      };
      nodeProto._registerIfAttached = undefined ;
      nodeProto._onTransformChanged = function (transformType) {
        this.emit("transform-changed", transformType);
      };
      nodeProto._onParentChanged = function (oldParent) {
        this.emit("parent-changed", oldParent);
      };
      nodeProto._onReAttach = function () {
        this._eventProcessor.reattach();
      };
      nodeProto._onEditorAttached = function (attached) {
      };
      nodeProto._onRemovePersistRootNode = function () {
        legacyCC.game.removePersistRootNode(this);
      };
      nodeProto._onDestroyComponents = function () {
        this._eventProcessor.destroy();
        const comps = this._components;
        for (let i = 0; i < comps.length; ++i) {
          comps[i]._destroyImmediate();
        }
      };
      nodeProto._onMobilityChanged = function () {
        this.emit("mobility-changed");
      };
      nodeProto._onLayerChanged = function (layer) {
        this.emit("layer-changed", layer);
      };
      nodeProto._onChildRemoved = function (child) {
        const removeAt = this._children.indexOf(child);
        if (removeAt < 0) {
          errorID(1633);
          return;
        }
        this._children.splice(removeAt, 1);
        this.emit("child-removed", child);
      };
      nodeProto._onChildAdded = function (child) {
        this._children.push(child);
        this.emit("child-added", child);
      };
      const oldPreDestroy = nodeProto._onPreDestroy;
      nodeProto._onPreDestroy = function _onPreDestroy() {
        const ret = oldPreDestroy.call(this);
        this.emit("node-destroyed", this);
        this._eventProcessor.destroy();
        const children = this._children;
        for (let i = 0; i < children.length; ++i) {
          children[i]._destroyImmediate();
        }
        const comps = this._components;
        for (let i = 0; i < comps.length; ++i) {
          comps[i]._destroyImmediate();
        }
        return ret;
      };
      nodeProto.destroyAllChildren = function destroyAllChildren() {
        const children = this._children;
        for (let i = 0, len = children.length; i < len; ++i) {
          children[i].destroy();
        }
      };
      nodeProto._onSiblingOrderChanged = function () {
        this.emit("sibling-order-changed");
      };
      nodeProto._onActivateNode = function (shouldActiveNow) {
        legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow);
      };
      nodeProto._onPostActivated = function (active) {
        if (this._eventMask & ACTIVE_ON) {
          this.emit("active-changed", this, active);
        }
        this._eventProcessor.setEnabled(active);
        if (active) {
          this.invalidateChildren(7);
          if (this._uiProps && this._uiProps.uiComp) {
            this._uiProps.uiComp.setNodeDirty();
            this._uiProps.uiComp.setTextureDirty();
            this._uiProps.uiComp.markForUpdateRenderData();
          }
        }
      };
      nodeProto._onLightProbeBakingChanged = function () {
        this.emit("light-probe-baking-changed");
      };
      NodeCls._findComponent = function (node, constructor) {
        const cls = constructor;
        const comps = node._components;
        if (cls._sealed) {
          for (let i = 0; i < comps.length; ++i) {
            const comp = comps[i];
            if (comp.constructor === constructor) {
              return comp;
            }
          }
        } else {
          for (let i = 0; i < comps.length; ++i) {
            const comp = comps[i];
            if (comp instanceof constructor) {
              return comp;
            }
          }
        }
        return null;
      };
      NodeCls._findComponents = function (node, constructor, components) {
        const cls = constructor;
        const comps = node._components;
        if (cls._sealed) {
          for (let i = 0; i < comps.length; ++i) {
            const comp = comps[i];
            if (comp.constructor === constructor) {
              components.push(comp);
            }
          }
        } else {
          for (let i = 0; i < comps.length; ++i) {
            const comp = comps[i];
            if (comp instanceof constructor) {
              components.push(comp);
            }
          }
        }
      };
      NodeCls._findChildComponent = function (children, constructor) {
        for (let i = 0; i < children.length; ++i) {
          const node = children[i];
          let comp = NodeCls._findComponent(node, constructor);
          if (comp) {
            return comp;
          }
          const childChildren = node.children;
          if (childChildren.length > 0) {
            comp = NodeCls._findChildComponent(childChildren, constructor);
            if (comp) {
              return comp;
            }
          }
        }
        return null;
      };
      NodeCls._findChildComponents = function (children, constructor, components) {
        for (let i = 0; i < children.length; ++i) {
          const node = children[i];
          NodeCls._findComponents(node, constructor, components);
          const childChildren = node.children;
          if (childChildren.length > 0) {
            NodeCls._findChildComponents(childChildren, constructor, components);
          }
        }
      };
      NodeCls.isNode = function (obj) {
        return obj instanceof jsb.Node && (obj.constructor === jsb.Node || !(obj instanceof legacyCC.Scene));
      };
      let _tempQuat = new Quat();
      nodeProto.setRTS = function setRTS(rot, pos, scale) {
        if (rot) {
          let val = _tempQuat;
          if (rot instanceof Quat) {
            val = rot;
          } else {
            Quat.fromEuler(val, rot.x, rot.y, rot.z);
          }
          _tempFloatArray[0] = 4;
          _tempFloatArray[1] = val.x;
          _tempFloatArray[2] = val.y;
          _tempFloatArray[3] = val.z;
          _tempFloatArray[4] = val.w;
          this._lrot.set(val.x, val.y, val.z, val.w);
        } else {
          _tempFloatArray[0] = 0;
        }
        if (pos) {
          _tempFloatArray[5] = 3;
          _tempFloatArray[6] = pos.x;
          _tempFloatArray[7] = pos.y;
          _tempFloatArray[8] = pos.z;
          this._lpos.set(pos.x, pos.y, pos.z);
        } else {
          _tempFloatArray[5] = 0;
        }
        if (scale) {
          _tempFloatArray[9] = 3;
          _tempFloatArray[10] = scale.x;
          _tempFloatArray[11] = scale.y;
          _tempFloatArray[12] = scale.z;
          this._lscale.set(scale.x, scale.y, scale.z);
        } else {
          _tempFloatArray[9] = 0;
        }
        this._setRTS();
      };
      nodeProto.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);
      };
      nodeProto.setPosition = function setPosition(val, y, z) {
        if (y === undefined && z === undefined) {
          _tempFloatArray[0] = 3;
          const pos = val;
          this._lpos.x = _tempFloatArray[1] = pos.x;
          this._lpos.y = _tempFloatArray[2] = pos.y;
          this._lpos.z = _tempFloatArray[3] = pos.z;
        } else if (z === undefined) {
          _tempFloatArray[0] = 2;
          this._lpos.x = _tempFloatArray[1] = val;
          this._lpos.y = _tempFloatArray[2] = y;
        } else {
          _tempFloatArray[0] = 3;
          this._lpos.x = _tempFloatArray[1] = val;
          this._lpos.y = _tempFloatArray[2] = y;
          this._lpos.z = _tempFloatArray[3] = z;
        }
        this._setPosition();
      };
      nodeProto.getRotation = function getRotation(out) {
        const lrot = this._lrot;
        if (out) {
          return Quat.set(out, lrot.x, lrot.y, lrot.z, lrot.w);
        }
        return Quat.copy(new Quat(), lrot);
      };
      nodeProto.setRotation = function setRotation(val, y, z, w) {
        if (y === undefined || z === undefined || w === undefined) {
          const rot = val;
          this._lrot.x = _tempFloatArray[0] = rot.x;
          this._lrot.y = _tempFloatArray[1] = rot.y;
          this._lrot.z = _tempFloatArray[2] = rot.z;
          this._lrot.w = _tempFloatArray[3] = rot.w;
        } else {
          this._lrot.x = _tempFloatArray[0] = val;
          this._lrot.y = _tempFloatArray[1] = y;
          this._lrot.z = _tempFloatArray[2] = z;
          this._lrot.w = _tempFloatArray[3] = w;
        }
        this._setRotation();
      };
      nodeProto.setRotationFromEuler = function setRotationFromEuler(val, y, zOpt) {
        const z = zOpt === undefined ? this._euler.z : zOpt;
        if (y === undefined) {
          const euler = val;
          this._euler.x = _tempFloatArray[0] = euler.x;
          this._euler.y = _tempFloatArray[1] = euler.y;
          this._euler.z = _tempFloatArray[2] = euler.z;
        } else {
          this._euler.x = _tempFloatArray[0] = val;
          this._euler.y = _tempFloatArray[1] = y;
          this._euler.z = _tempFloatArray[2] = z;
        }
        this._setRotationFromEuler();
      };
      nodeProto.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);
      };
      nodeProto.setScale = function setScale(val, y, z) {
        if (y === undefined && z === undefined) {
          _tempFloatArray[0] = 3;
          const scale = val;
          this._lscale.x = _tempFloatArray[1] = scale.x;
          this._lscale.y = _tempFloatArray[2] = scale.y;
          this._lscale.z = _tempFloatArray[3] = scale.z;
        } else if (z === undefined) {
          _tempFloatArray[0] = 2;
          this._lscale.x = _tempFloatArray[1] = val;
          this._lscale.y = _tempFloatArray[2] = y;
        } else {
          _tempFloatArray[0] = 3;
          this._lscale.x = _tempFloatArray[1] = val;
          this._lscale.y = _tempFloatArray[2] = y;
          this._lscale.z = _tempFloatArray[3] = z;
        }
        this._setScale();
      };
      nodeProto.getWorldPosition = function getWorldPosition(out) {
        this._getWorldPosition();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.getWorldRotation = function getWorldRotation(out) {
        this._getWorldRotation();
        out = out || new Quat();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3]);
      };
      nodeProto.getWorldScale = function getWorldScale(out) {
        this._getWorldScale();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.getWorldMatrix = function getWorldMatrix(out) {
        this._getWorldMatrix();
        out = out || new Mat4();
        fillMat4WithTempFloatArray(out);
        return out;
      };
      nodeProto.getEulerAngles = function getEulerAngles(out) {
        this._getEulerAngles();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.getForward = function getForward(out) {
        this._getForward();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.getUp = function getUp(out) {
        this._getUp();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.getRight = function getRight(out) {
        this._getRight();
        out = out || new Vec3();
        return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
      };
      nodeProto.inverseTransformPoint = function inverseTransformPoint(out, p) {
        _tempFloatArray[0] = p.x;
        _tempFloatArray[1] = p.y;
        _tempFloatArray[2] = p.z;
        this._inverseTransformPoint();
        out.x = _tempFloatArray[0];
        out.y = _tempFloatArray[1];
        out.z = _tempFloatArray[2];
        return out;
      };
      nodeProto.getWorldRT = function getWorldRT(out) {
        out = out || new Mat4();
        this._getWorldRT();
        fillMat4WithTempFloatArray(out);
        return out;
      };
      nodeProto.getWorldRS = function getWorldRS(out) {
        out = out || new Mat4();
        this._getWorldRS();
        fillMat4WithTempFloatArray(out);
        return out;
      };
      nodeProto.isTransformDirty = function () {
        return this._transformFlags !== 0;
      };
      Object.defineProperty(nodeProto, 'name', {
        configurable: true,
        enumerable: true,
        get() {
          return this._name;
        },
        set(v) {
          this._name = v;
        }
      });
      Object.defineProperty(nodeProto, 'position', {
        configurable: true,
        enumerable: true,
        get() {
          return this._lpos;
        },
        set(v) {
          this.setPosition(v);
        }
      });
      Object.defineProperty(nodeProto, 'rotation', {
        configurable: true,
        enumerable: true,
        get() {
          return this._lrot;
        },
        set(v) {
          this.setRotation(v);
        }
      });
      Object.defineProperty(nodeProto, 'scale', {
        configurable: true,
        enumerable: true,
        get() {
          return this._lscale;
        },
        set(v) {
          this.setScale(v);
        }
      });
      Object.defineProperty(nodeProto, 'worldPosition', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldPosition();
        },
        set(v) {
          this.setWorldPosition(v);
        }
      });
      Object.defineProperty(nodeProto, 'worldRotation', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldRotation();
        },
        set(v) {
          this.setWorldRotation(v);
        }
      });
      Object.defineProperty(nodeProto, 'worldScale', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldScale();
        },
        set(v) {
          this.setWorldScale(v);
        }
      });
      Object.defineProperty(nodeProto, '_pos', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldPosition();
        }
      });
      Object.defineProperty(nodeProto, '_rot', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldRotation();
        }
      });
      Object.defineProperty(nodeProto, '_scale', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldScale();
        }
      });
      Object.defineProperty(nodeProto, 'eulerAngles', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getEulerAngles();
        },
        set(v) {
          this.setRotationFromEuler(v.x, v.y, v.z);
        }
      });
      Object.defineProperty(nodeProto, 'worldMatrix', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldMatrix();
        }
      });
      Object.defineProperty(nodeProto, '_mat', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getWorldMatrix();
        }
      });
      Object.defineProperty(nodeProto, 'activeInHierarchy', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint8Arr[0] != 0;
        },
        set(v) {
          this._sharedUint8Arr[0] = v ? 1 : 0;
        }
      });
      Object.defineProperty(nodeProto, '_activeInHierarchy', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint8Arr[0] != 0;
        },
        set(v) {
          this._sharedUint8Arr[0] = v ? 1 : 0;
        }
      });
      Object.defineProperty(nodeProto, 'layer', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint32Arr[1];
        },
        set(v) {
          this._sharedUint32Arr[1] = v;
          if (this._uiProps && this._uiProps.uiComp) {
            this._uiProps.uiComp.setNodeDirty();
            this._uiProps.uiComp.markForUpdateRenderData();
          }
          this.emit("layer-changed", v);
        }
      });
      Object.defineProperty(nodeProto, '_layer', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint32Arr[1];
        },
        set(v) {
          this._sharedUint32Arr[1] = v;
        }
      });
      Object.defineProperty(nodeProto, '_eventMask', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint32Arr[0];
        },
        set(v) {
          this._sharedUint32Arr[0] = v;
        }
      });
      Object.defineProperty(nodeProto, '_siblingIndex', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedInt32Arr[0];
        },
        set(v) {
          this._sharedInt32Arr[0] = v;
        }
      });
      Object.defineProperty(nodeProto, 'prefab', {
        configurable: true,
        enumerable: true,
        get() {
          return this._prefab;
        }
      });
      Object.defineProperty(nodeProto, 'siblingIndex', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedInt32Arr[0];
        },
        set(v) {
          this._sharedInt32Arr[0] = v;
        }
      });
      nodeProto.getSiblingIndex = function getSiblingIndex() {
        return this._sharedInt32Arr[0];
      };
      Object.defineProperty(nodeProto, '_transformFlags', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint32Arr[2];
        },
        set(v) {
          this._sharedUint32Arr[2] = v;
        }
      });
      Object.defineProperty(nodeProto, '_active', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint8Arr[1] != 0;
        },
        set(v) {
          this._sharedUint8Arr[1] = v ? 1 : 0;
        }
      });
      Object.defineProperty(nodeProto, 'active', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint8Arr[1] != 0;
        },
        set(v) {
          this.setActive(!!v);
        }
      });
      Object.defineProperty(nodeProto, '_static', {
        configurable: true,
        enumerable: true,
        get() {
          return this._sharedUint8Arr[2] != 0;
        },
        set(v) {
          this._sharedUint8Arr[2] = v ? 1 : 0;
        }
      });
      Object.defineProperty(nodeProto, 'forward', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getForward();
        },
        set(dir) {
          this.setForward(dir);
        }
      });
      Object.defineProperty(nodeProto, 'up', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getUp();
        }
      });
      Object.defineProperty(nodeProto, 'right', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getRight();
        }
      });
      Object.defineProperty(nodeProto, 'eventProcessor', {
        configurable: true,
        enumerable: true,
        get() {
          return this._eventProcessor;
        }
      });
      Object.defineProperty(nodeProto, 'components', {
        configurable: true,
        enumerable: true,
        get() {
          return this._components;
        }
      });
      Object.defineProperty(nodeProto, '_parent', {
        configurable: true,
        enumerable: true,
        get() {
          this._parentRef = this._parentInternal;
          return this._parentRef;
        },
        set(v) {
          this._parentRef = this._parentInternal = v;
        }
      });
      Object.defineProperty(nodeProto, 'parent', {
        configurable: true,
        enumerable: true,
        get() {
          this._parentRef = this.getParent();
          return this._parentRef;
        },
        set(v) {
          this._parentRef = v;
          this.setParent(v);
        }
      });
      Object.defineProperty(nodeProto, 'children', {
        configurable: true,
        enumerable: true,
        get() {
          return this._children;
        },
        set(v) {
          this._children = v;
        }
      });
      Object.defineProperty(nodeProto, 'scene', {
        configurable: true,
        enumerable: true,
        get() {
          return this._scene;
        }
      });
      Object.defineProperty(nodeProto, 'id', {
        configurable: true,
        enumerable: true,
        set(id) {
          this._id = id;
        }
      });
      nodeProto.rotate = function (rot, ns) {
        _tempFloatArray[1] = rot.x;
        _tempFloatArray[2] = rot.y;
        _tempFloatArray[3] = rot.z;
        _tempFloatArray[4] = rot.w;
        if (ns) {
          _tempFloatArray[5] = ns;
          _tempFloatArray[0] = 5;
        } else {
          _tempFloatArray[0] = 4;
        }
        this._rotateForJS();
        const lrot = this._lrot;
        lrot.x = _tempFloatArray[0];
        lrot.y = _tempFloatArray[1];
        lrot.z = _tempFloatArray[2];
        lrot.w = _tempFloatArray[3];
      };
      nodeProto.addChild = function (child) {
        child.setParent(this);
      };
      nodeProto.insertChild = function (child, siblingIndex) {
        child.parent = this;
        child.setSiblingIndex(siblingIndex);
      };
      nodeProto[serializeTag] = function (serializationOutput, context) {
        {
          serializationOutput.writeThis();
        }
        const isMountedChild = () => {
          var _this$editorExtrasTag;
          return !!((_this$editorExtrasTag = this[editorExtrasTag]) !== null && _this$editorExtrasTag !== void 0 && _this$editorExtrasTag.mountedRoot);
        };
        const isSyncPrefab = () => {
          var _this$_prefab, _this$_prefab$root, _this$_prefab$root$_p, _this$_prefab2;
          return ((_this$_prefab = this._prefab) === null || _this$_prefab === void 0 ? void 0 : (_this$_prefab$root = _this$_prefab.root) === null || _this$_prefab$root === void 0 ? void 0 : (_this$_prefab$root$_p = _this$_prefab$root._prefab) === null || _this$_prefab$root$_p === void 0 ? void 0 : _this$_prefab$root$_p.instance) && ((this === null || this === void 0 ? void 0 : (_this$_prefab2 = this._prefab) === null || _this$_prefab2 === void 0 ? void 0 : _this$_prefab2.instance) || !isMountedChild());
        };
        const canDiscardByPrefabRoot = () => !(context.customArguments[reserveContentsForAllSyncablePrefabTag] || !isSyncPrefab() || context.root === this);
        if (canDiscardByPrefabRoot()) {
          var _this$_prefab3;
          const isRoot = ((_this$_prefab3 = this._prefab) === null || _this$_prefab3 === void 0 ? void 0 : _this$_prefab3.root) === this;
          if (isRoot) {
            let isNestedPrefab = false;
            let parent = this.getParent();
            while (parent) {
              var _parent$_prefab;
              const nestedRoots = (_parent$_prefab = parent._prefab) === null || _parent$_prefab === void 0 ? void 0 : _parent$_prefab.nestedPrefabInstanceRoots;
              if (nestedRoots && nestedRoots.length > 0) {
                isNestedPrefab = !nestedRoots.some(root => root === this);
                break;
              }
              parent = parent.getParent();
            }
            if (!isNestedPrefab) {
              serializationOutput.writeProperty('_objFlags', this._objFlags);
              serializationOutput.writeProperty('_parent', this._parent);
              serializationOutput.writeProperty('_prefab', this._prefab);
              if (context.customArguments.keepNodeUuid) {
                serializationOutput.writeProperty('_id', this._id);
              }
            }
            serializationOutput.writeProperty(editorExtrasTag, this[editorExtrasTag]);
          }
        } else {
          serializationOutput.writeThis();
        }
      };
      nodeProto._onActiveNode = function (shouldActiveNow) {
        legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow);
      };
      nodeProto._onBatchCreated = function (dontSyncChildPrefab) {
        if (this._eventMask & ACTIVE_ON) {
          if (!this._activeInHierarchy) {
            this.emit("active-changed", this, false);
          }
        }
        this.hasChangedFlags = TRANSFORMBIT_TRS;
        const children = this._children;
        const len = children.length;
        let child;
        for (let i = 0; i < len; ++i) {
          child = children[i];
          child._siblingIndex = i;
          child._onBatchCreated(dontSyncChildPrefab);
        }
        syncNodeValues(this);
      };
      nodeProto._onSceneUpdated = function (scene) {
        this._scene = scene;
      };
      nodeProto._onLocalPositionUpdated = function (x, y, z) {
        const lpos = this._lpos;
        lpos.x = x;
        lpos.y = y;
        lpos.z = z;
      };
      nodeProto._onLocalRotationUpdated = function (x, y, z, w) {
        const lrot = this._lrot;
        lrot.x = x;
        lrot.y = y;
        lrot.z = z;
        lrot.w = w;
      };
      nodeProto._onLocalScaleUpdated = function (x, y, z) {
        const lscale = this._lscale;
        lscale.x = x;
        lscale.y = y;
        lscale.z = z;
      };
      nodeProto._onLocalPositionRotationScaleUpdated = function (px, py, pz, rx, ry, rz, rw, sx, sy, sz) {
        const lpos = this._lpos;
        lpos.x = px;
        lpos.y = py;
        lpos.z = pz;
        const lrot = this._lrot;
        lrot.x = rx;
        lrot.y = ry;
        lrot.z = rz;
        lrot.w = rw;
        const lscale = this._lscale;
        lscale.x = sx;
        lscale.y = sy;
        lscale.z = sz;
      };
      nodeProto._instantiate = function (cloned, isSyncedNode) {
        if (!cloned) {
          cloned = legacyCC.instantiate._clone(this, this);
        }
        cloned._prefab;
        cloned._parent = null;
        cloned._onBatchCreated(isSyncedNode);
        return cloned;
      };
      nodeProto._onSiblingIndexChanged = function (index) {
        const siblings = this._parent._children;
        index = index !== -1 ? index : siblings.length - 1;
        const 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._eventProcessor.onUpdatingSiblingIndex();
        }
      };
      nodeProto._ctor = function (name) {
        this.__nativeRefs = {};
        this._parentRef = null;
        this.__jsb_ref_id = undefined;
        this._iN$t = null;
        this.__editorExtras__ = {
          editorOnly: true
        };
        this._components = [];
        this._eventProcessor = new legacyCC.NodeEventProcessor(this);
        this._uiProps = new NodeUIProperties(this);
        const sharedArrayBuffer = this._initAndReturnSharedBuffer();
        this._sharedUint32Arr = new Uint32Array(sharedArrayBuffer, 0, 3);
        this._sharedInt32Arr = new Int32Array(sharedArrayBuffer, 12, 1);
        this._sharedUint8Arr = new Uint8Array(sharedArrayBuffer, 16, 3);
        this._sharedUint32Arr[1] = Layers.Enum.DEFAULT;
        this._scene = null;
        this._prefab = null;
        this._originalSceneId = '';
        this._children = [];
        this._lpos = new Vec3();
        this._lrot = new Quat();
        this._lscale = new Vec3(1, 1, 1);
        this._euler = new Vec3();
        this._registeredNodeEventTypeMask = 0;
      };
      patch_cc_Node({
        Node: Node$1,
        Vec3,
        Quat,
        MobilityMode,
        Layers
      });

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

      const _arrayPool = new Pool(() => new Array(16), 3);
      let _currentHovered = null;
      const pos = new Vec2();
      const _touchEvents = ["touch-start", "touch-move", "touch-end", "touch-cancel"];
      const _mouseEvents = ["mouse-down", "mouse-enter", "mouse-move", "mouse-leave", "mouse-up", "mouse-wheel"];
      class NodeEventProcessor {
        get isEnabled() {
          return this._isEnabled;
        }
        get node() {
          return this._node;
        }
        constructor(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._isMouseLeaveWindow = false;
          this._node = node;
        }
        setEnabled(value, recursive = false) {
          if (this._isEnabled === value) {
            return;
          }
          this._isEnabled = value;
          const node = this.node;
          const children = node.children;
          if (value) {
            this._attachMask();
          }
          NodeEventProcessor.callbacksInvoker.emit(2);
          if (recursive && children.length > 0) {
            for (let i = 0; i < children.length; ++i) {
              const child = children[i];
              child.eventProcessor.setEnabled(value, true);
            }
          }
        }
        reattach() {
          let currentMaskList;
          this.node.walk(node => {
            if (!currentMaskList) {
              currentMaskList = this._searchComponentsInParent(NodeEventProcessor._maskComp);
            }
            node.eventProcessor.maskList = currentMaskList;
          });
        }
        destroy() {
          if (_currentHovered === this._node) {
            _currentHovered = null;
          }
          if (this.capturingTarget) this.capturingTarget.clear();
          if (this.bubblingTarget) this.bubblingTarget.clear();
          NodeEventProcessor.callbacksInvoker.emit(1, this);
          if (this._dispatchingTouch) {
            const cancelEvent = new EventTouch([this._dispatchingTouch], true, "touch-cancel");
            cancelEvent.touch = this._dispatchingTouch;
            this.dispatchEvent(cancelEvent);
            this._dispatchingTouch = null;
          }
        }
        on(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          let 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;
        }
        once(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          let 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;
        }
        off(type, callback, target, useCapture) {
          var _invoker;
          useCapture = !!useCapture;
          let invoker;
          if (useCapture) {
            invoker = this.capturingTarget;
          } else {
            invoker = this.bubblingTarget;
          }
          (_invoker = invoker) === null || _invoker === void 0 ? void 0 : _invoker.off(type, callback, target);
        }
        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(1, this);
          }
        }
        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);
        }
        dispatchEvent(event) {
          const owner = this.node;
          let target;
          let i = 0;
          event.target = owner;
          const cachedArray = _arrayPool.alloc();
          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) {
                _arrayPool.free(cachedArray);
                return;
              }
            }
          }
          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) {
            cachedArray.length = 0;
            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) {
                  _arrayPool.free(cachedArray);
                  return;
                }
              }
            }
          }
          _arrayPool.free(cachedArray);
        }
        hasEventListener(type, callback, target) {
          let 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;
        }
        getCapturingTargets(type, targets) {
          let 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;
          }
        }
        getBubblingTargets(type, targets) {
          let 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;
          }
        }
        onUpdatingSiblingIndex() {
          NodeEventProcessor.callbacksInvoker.emit(2);
        }
        _searchComponentsInParent(ctor) {
          const node = this.node;
          if (ctor) {
            let index = 0;
            let list = [];
            for (let curr = node; curr && Node$1.isNode(curr); curr = curr.parent, ++index) {
              const comp = curr.getComponent(ctor);
              if (comp) {
                const next = {
                  index,
                  comp
                };
                if (list) {
                  list.push(next);
                } else {
                  list = [next];
                }
              }
            }
            return list.length > 0 ? list : null;
          }
          return null;
        }
        _attachMask() {
          this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp);
        }
        _isTouchEvent(type) {
          const index = _touchEvents.indexOf(type);
          return index !== -1;
        }
        _isMouseEvent(type) {
          const index = _mouseEvents.indexOf(type);
          return index !== -1;
        }
        _hasTouchListeners() {
          for (let i = 0; i < _touchEvents.length; ++i) {
            const eventType = _touchEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        }
        _hasMouseListeners() {
          for (let i = 0; i < _mouseEvents.length; ++i) {
            const eventType = _mouseEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        }
        _hasPointerListeners() {
          const has = this._hasTouchListeners();
          if (has) {
            return true;
          }
          return this._hasMouseListeners();
        }
        _tryEmittingAddEvent(typeToAdd) {
          const isTouchEvent = this._isTouchEvent(typeToAdd);
          const isMouseEvent = this._isMouseEvent(typeToAdd);
          if (isTouchEvent) {
            this.shouldHandleEventTouch = true;
          } else if (isMouseEvent) {
            this.shouldHandleEventMouse = true;
          }
          if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) {
            NodeEventProcessor.callbacksInvoker.emit(0, this);
          }
        }
        _newCallbacksInvoker() {
          const callbacksInvoker = new CallbacksInvoker();
          callbacksInvoker._registerOffCallback(() => {
            if (this.shouldHandleEventTouch && !this._hasTouchListeners()) {
              this.shouldHandleEventTouch = false;
            }
            if (this.shouldHandleEventMouse && !this._hasMouseListeners()) {
              this.shouldHandleEventMouse = false;
            }
            if (!this._hasPointerListeners()) {
              NodeEventProcessor.callbacksInvoker.emit(1, this);
            }
          });
          return callbacksInvoker;
        }
        _handleEventMouse(eventMouse) {
          switch (eventMouse.type) {
            case "mouse-down":
              return this._handleMouseDown(eventMouse);
            case "mouse-move":
              return this._handleMouseMove(eventMouse);
            case "mouse-up":
              return this._handleMouseUp(eventMouse);
            case "mouse-wheel":
              return this._handleMouseWheel(eventMouse);
            case "mouse-leave-window":
              return this._handleMouseLeave(eventMouse);
            case "mouse-enter-window":
              return this._handleMouseEnter(eventMouse);
            default:
              return false;
          }
        }
        _handleMouseDown(event) {
          const node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = "mouse-down";
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        }
        _handleMouseMove(event) {
          const node = this._node;
          if (!node || !node._uiProps.uiTransformComp || this._isMouseLeaveWindow) {
            return false;
          }
          event.getLocation(pos);
          const hit = node._uiProps.uiTransformComp.hitTest(pos, event.windowId);
          if (hit) {
            if (!this.previousMouseIn) {
              if (_currentHovered && _currentHovered !== node) {
                event.type = "mouse-leave";
                _currentHovered.dispatchEvent(event);
                _currentHovered.eventProcessor.previousMouseIn = false;
              }
              _currentHovered = node;
              event.type = "mouse-enter";
              node.dispatchEvent(event);
              this.previousMouseIn = true;
            }
            event.type = "mouse-move";
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          } else if (this.previousMouseIn) {
            event.type = "mouse-leave";
            node.dispatchEvent(event);
            this.previousMouseIn = false;
            _currentHovered = null;
          }
          return false;
        }
        _handleMouseUp(event) {
          const node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = "mouse-up";
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        }
        _handleMouseWheel(event) {
          const node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = "mouse-wheel";
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        }
        _handleMouseLeave(event) {
          this._isMouseLeaveWindow = true;
          if (this.previousMouseIn) {
            event.type = "mouse-leave";
            this._node.dispatchEvent(event);
            this.previousMouseIn = false;
            _currentHovered = null;
          }
          return false;
        }
        _handleMouseEnter(event) {
          this._isMouseLeaveWindow = false;
          return false;
        }
        _handleEventTouch(eventTouch) {
          try {
            switch (eventTouch.type) {
              case "touch-start":
                return this._handleTouchStart(eventTouch);
              case "touch-move":
                return this._handleTouchMove(eventTouch);
              case "touch-end":
                return this._handleTouchEnd(eventTouch);
              case "touch-cancel":
                return this._handleTouchCancel(eventTouch);
              default:
                return false;
            }
          } catch (err) {
            this.claimedTouchIdList.length = 0;
            throw err;
          }
        }
        _handleTouchStart(event) {
          const node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = "touch-start";
            event.bubbles = true;
            this._dispatchingTouch = event.touch;
            node.dispatchEvent(event);
            return true;
          }
          return false;
        }
        _handleTouchMove(event) {
          const node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.type = "touch-move";
          event.bubbles = true;
          this._dispatchingTouch = event.touch;
          node.dispatchEvent(event);
          return true;
        }
        _handleTouchEnd(event) {
          const node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = "touch-end";
          } else {
            event.type = "touch-cancel";
          }
          event.bubbles = true;
          node.dispatchEvent(event);
          this._dispatchingTouch = null;
        }
        _handleTouchCancel(event) {
          const node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.type = "touch-cancel";
          event.bubbles = true;
          node.dispatchEvent(event);
          this._dispatchingTouch = null;
        }
      }
      NodeEventProcessor._maskComp = null;
      NodeEventProcessor.callbacksInvoker = new CallbacksInvoker();
      legacyCC.NodeEventProcessor = NodeEventProcessor;

      const textureCubeProto = jsb.TextureCube.prototype;
      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 = {}));
      textureCubeProto.createNode = null;
      const TextureCube = exports("TextureCube", jsb.TextureCube);
      TextureCube.Filter = TextureFilter;
      TextureCube.PixelFormat = PixelFormat;
      TextureCube.WrapMode = WrapMode$1;
      textureCubeProto._ctor = function () {
        jsb.SimpleTexture.prototype._ctor.apply(this, arguments);
        this._mipmaps = null;
        this._mipmapAtlas = null;
      };
      Object.defineProperty(textureCubeProto, 'mipmaps', {
        get() {
          return this._mipmaps;
        },
        set(value) {
          this._mipmaps = value;
          this.setMipmaps(value);
        }
      });
      Object.defineProperty(textureCubeProto, 'image', {
        get() {
          return this._mipmaps.length === 0 ? null : this._mipmaps[0];
        },
        set(value) {
          this.mipmaps = value ? [value] : [];
        }
      });
      const oldOnLoaded$1 = textureCubeProto.onLoaded;
      textureCubeProto.onLoaded = function () {
        if (this._mipmapMode === 2) {
          this.setMipmapAtlasForJS(this._mipmapAtlas);
        } else {
          this.setMipmapsForJS(this._mipmaps);
        }
        oldOnLoaded$1.apply(this);
      };
      textureCubeProto._serialize = function (ctxForExporting) {
        return null;
      };
      textureCubeProto._deserialize = function (serializedData, handle) {
        const data = serializedData;
        jsb.TextureBase.prototype._deserialize.call(this, data.base, handle);
        this.isRGBE = data.rgbe;
        if (data.mipmapMode != undefined) {
          this._mipmapMode = data.mipmapMode;
        }
        if (this._mipmapMode === 2) {
          const mipmapAtlas = data.mipmapAtlas;
          const mipmapLayout = data.mipmapLayout;
          this._mipmapAtlas = {
            atlas: {},
            layout: mipmapLayout
          };
          this._mipmapAtlas.atlas = {
            front: new jsb.ImageAsset(),
            back: new jsb.ImageAsset(),
            left: new jsb.ImageAsset(),
            right: new jsb.ImageAsset(),
            top: new jsb.ImageAsset(),
            bottom: new jsb.ImageAsset()
          };
          if (mipmapAtlas) {
            const imageAssetClassId = getClassId(jsb.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 (let i = 0; i < data.mipmaps.length; ++i) {
            this._mipmaps[i] = {
              front: new jsb.ImageAsset(),
              back: new jsb.ImageAsset(),
              left: new jsb.ImageAsset(),
              right: new jsb.ImageAsset(),
              top: new jsb.ImageAsset(),
              bottom: new jsb.ImageAsset()
            };
            const mipmap = data.mipmaps[i];
            const imageAssetClassId = getClassId(jsb.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);
          }
        }
      };
      cclegacy.TextureCube = jsb.TextureCube;
      patch_cc_TextureCube({
        TextureCube,
        MipmapMode
      });

      let 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 = {}));
      const Model = jsb.Model;
      const modelProto = Model.prototype;
      modelProto._ctor = function () {
        this._device = deviceManager.gfxDevice;
      };
      const oldCreateBoundingShape = modelProto.createBoundingShape;
      modelProto.createBoundingShape = function (minPos, maxPos) {
        if (!minPos || !maxPos) {
          return;
        }
        oldCreateBoundingShape.call(this, minPos, maxPos);
      };

      const SubModel = jsb.SubModel;

      let CameraFOVAxis;
      (function (CameraFOVAxis) {
        CameraFOVAxis[CameraFOVAxis["VERTICAL"] = 0] = "VERTICAL";
        CameraFOVAxis[CameraFOVAxis["HORIZONTAL"] = 1] = "HORIZONTAL";
      })(CameraFOVAxis || (CameraFOVAxis = {}));
      let CameraProjection;
      (function (CameraProjection) {
        CameraProjection[CameraProjection["ORTHO"] = 0] = "ORTHO";
        CameraProjection[CameraProjection["PERSPECTIVE"] = 1] = "PERSPECTIVE";
      })(CameraProjection || (CameraProjection = {}));
      let 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 = {}));
      let 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 = {}));
      let 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 = {}));
      let 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 = {}));
      let 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 = {}));
      let 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 = {}));
      let SkyBoxFlagValue;
      (function (SkyBoxFlagValue) {
        SkyBoxFlagValue[SkyBoxFlagValue["VALUE"] = 8] = "VALUE";
      })(SkyBoxFlagValue || (SkyBoxFlagValue = {}));
      const SKYBOX_FLAG = 8;
      const Camera$1 = jsb.Camera;
      const cameraProto = jsb.Camera.prototype;
      Object.defineProperty(Camera$1, "standardExposureValue", {
        configurable: true,
        enumerable: true,
        get() {
          return Camera$1.getStandardExposureValue();
        }
      });
      Object.defineProperty(Camera$1, "standardLightMeterScale", {
        configurable: true,
        enumerable: true,
        get() {
          return Camera$1.getStandardLightMeterScale();
        }
      });
      Object.defineProperty(cameraProto, 'matView', {
        configurable: true,
        enumerable: true,
        get() {
          this.getMatView();
          fillMat4WithTempFloatArray(this._matView);
          return this._matView;
        }
      });
      Object.defineProperty(cameraProto, 'matProj', {
        configurable: true,
        enumerable: true,
        get() {
          this.getMatProj();
          fillMat4WithTempFloatArray(this._matProj);
          return this._matProj;
        }
      });
      Object.defineProperty(cameraProto, 'matProjInv', {
        configurable: true,
        enumerable: true,
        get() {
          this.getMatProjInv();
          fillMat4WithTempFloatArray(this._matProjInv);
          return this._matProjInv;
        }
      });
      Object.defineProperty(cameraProto, 'matViewProj', {
        configurable: true,
        enumerable: true,
        get() {
          this.getMatViewProj();
          fillMat4WithTempFloatArray(this._matViewProj);
          return this._matViewProj;
        }
      });
      Object.defineProperty(cameraProto, 'matViewProjInv', {
        configurable: true,
        enumerable: true,
        get() {
          this.getMatViewProjInv();
          fillMat4WithTempFloatArray(this._matViewProjInv);
          return this._matViewProjInv;
        }
      });
      const oldInitialize = cameraProto.initialize;
      cameraProto.initialize = function initialize() {
        oldInitialize.apply(this, arguments);
        this._matView = new Mat4();
        this._matProj = new Mat4();
        this._matProjInv = new Mat4();
        this._matViewProj = new Mat4();
        this._matViewProjInv = new Mat4();
      };
      const oldScreenPointToRay = cameraProto.screenPointToRay;
      const oldScreenToWorld = cameraProto.screenToWorld;
      const oldWorldToScreen = cameraProto.worldToScreen;
      const oldWorldMatrixToScreen = cameraProto.worldMatrixToScreen;
      cameraProto.screenPointToRay = function screenPointToRay(out, x, y) {
        _tempFloatArray[0] = x;
        _tempFloatArray[1] = y;
        oldScreenPointToRay.call(this);
        out.o.x = _tempFloatArray[0];
        out.o.y = _tempFloatArray[1];
        out.o.z = _tempFloatArray[2];
        out.d.x = _tempFloatArray[3];
        out.d.y = _tempFloatArray[4];
        out.d.z = _tempFloatArray[5];
        return out;
      };
      cameraProto.screenToWorld = function screenToWorld(out, screenPos) {
        _tempFloatArray[0] = screenPos.x;
        _tempFloatArray[1] = screenPos.y;
        _tempFloatArray[2] = screenPos.z;
        oldScreenToWorld.call(this);
        Vec3.set(out, _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
        return out;
      };
      cameraProto.worldToScreen = function worldToScreen(out, worldPos) {
        _tempFloatArray[0] = worldPos.x;
        _tempFloatArray[1] = worldPos.y;
        _tempFloatArray[2] = worldPos.z;
        oldWorldToScreen.call(this);
        Vec3.set(out, _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]);
        return out;
      };
      cameraProto.worldMatrixToScreen = function worldMatrixToScreen(out, worldMatrix, width, height) {
        _tempFloatArray[0] = worldMatrix.m00;
        _tempFloatArray[1] = worldMatrix.m01;
        _tempFloatArray[2] = worldMatrix.m02;
        _tempFloatArray[3] = worldMatrix.m03;
        _tempFloatArray[4] = worldMatrix.m04;
        _tempFloatArray[5] = worldMatrix.m05;
        _tempFloatArray[6] = worldMatrix.m06;
        _tempFloatArray[7] = worldMatrix.m07;
        _tempFloatArray[8] = worldMatrix.m08;
        _tempFloatArray[9] = worldMatrix.m09;
        _tempFloatArray[10] = worldMatrix.m10;
        _tempFloatArray[11] = worldMatrix.m11;
        _tempFloatArray[12] = worldMatrix.m12;
        _tempFloatArray[13] = worldMatrix.m13;
        _tempFloatArray[14] = worldMatrix.m14;
        _tempFloatArray[15] = worldMatrix.m15;
        _tempFloatArray[16] = width;
        _tempFloatArray[17] = height;
        oldWorldMatrixToScreen.call(this);
        fillMat4WithTempFloatArray(out);
        return out;
      };

      let ProbeClearFlag;
      (function (ProbeClearFlag) {
        ProbeClearFlag[ProbeClearFlag["SKYBOX"] = SKYBOX_FLAG | 6] = "SKYBOX";
        ProbeClearFlag[ProbeClearFlag["SOLID_COLOR"] = 7] = "SOLID_COLOR";
      })(ProbeClearFlag || (ProbeClearFlag = {}));
      let ProbeType;
      (function (ProbeType) {
        ProbeType[ProbeType["CUBE"] = 0] = "CUBE";
        ProbeType[ProbeType["PLANAR"] = 1] = "PLANAR";
      })(ProbeType || (ProbeType = {}));
      const ReflectionProbe = jsb.ReflectionProbe;
      const reflectionProbeProto = jsb.ReflectionProbe.prototype;
      reflectionProbeProto._ctor = function (id) {
        this._probeId = id;
      };

      const LODData = jsb.LODData;
      const LODGroup = jsb.LODGroup;
      const Ambient = jsb.Ambient;
      cclegacy.Ambient = Ambient;
      Ambient.SUN_ILLUM = 65000.0;
      Ambient.SKY_ILLUM = 20000.0;
      function ColorTemperatureToRGB(rgb, kelvin) {
        if (kelvin < 1000.0) {
          kelvin = 1000.0;
        } else if (kelvin > 15000.0) {
          kelvin = 15000.0;
        }
        const kSqr = kelvin * kelvin;
        const u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr);
        const v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr);
        const d = 2.0 * u - 8.0 * v + 4.0;
        const x = 3.0 * u / d;
        const y = 2.0 * v / d;
        const z = 1.0 - x - y;
        const X = 1.0 / y * x;
        const 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;
      }
      let 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 = {}));
      const nt2lm = size => 4 * Math.PI * Math.PI * size * size;
      const Light = jsb.Light;
      cclegacy.Light = jsb.Light;
      const DirectionalLight = jsb.DirectionalLight;
      cclegacy.DirectionalLight = jsb.DirectionalLight;
      const SpotLight = jsb.SpotLight;
      cclegacy.SpotLight = jsb.SpotLight;
      const SphereLight = jsb.SphereLight;
      cclegacy.SphereLight = jsb.SphereLight;
      const PointLight = jsb.PointLight;
      cclegacy.PointLight = jsb.PointLight;
      const RangedDirectionalLight = jsb.RangedDirectionalLight;
      cclegacy.RangedDirectionalLight = jsb.RangedDirectionalLight;
      const FogType$1 = Enum({
        LINEAR: 0,
        EXP: 1,
        EXP_SQUARED: 2,
        LAYERED: 3
      });
      const FOG_TYPE_NONE = FogType$1.LAYERED + 1;
      const FogInfo$1 = jsb.FogInfo;
      const Fog = jsb.Fog;
      cclegacy.Fog = Fog;
      const ShadowSize$1 = Enum({
        Low_256x256: 256,
        Medium_512x512: 512,
        High_1024x1024: 1024,
        Ultra_2048x2048: 2048
      });
      const ShadowType$2 = Enum({
        Planar: 0,
        ShadowMap: 1
      });
      const PCFType = Enum({
        HARD: 0,
        SOFT: 1,
        SOFT_2X: 2,
        SOFT_4X: 3
      });
      const CSMLevel = Enum({
        LEVEL_1: 1,
        LEVEL_2: 2,
        LEVEL_3: 3,
        LEVEL_4: 4
      });
      const CSMOptimizationMode = Enum({
        NONE: 1,
        RemoveDuplicates: 2,
        DisableRotationFix: 3
      });
      const EnvironmentLightingType = Enum({
        HEMISPHERE_DIFFUSE: 0,
        AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION: 1,
        DIFFUSEMAP_WITH_REFLECTION: 2
      });
      const ToneMappingType = Enum({
        DEFAULT: 0,
        LINEAR: 1
      });
      const ShadowsInfo$1 = jsb.ShadowsInfo;
      const Shadows$1 = jsb.Shadows;
      cclegacy.Shadows = Shadows$1;
      Object.defineProperty(Shadows$1, "MAX_FAR", {
        configurable: true,
        enumerable: true,
        get() {
          return 2000.0;
        }
      });
      const COEFFICIENT_OF_EXPANSION = 2.0 * Math.sqrt(3.0);
      Object.defineProperty(Shadows$1, 'COEFFICIENT_OF_EXPANSION', {
        configurable: true,
        enumerable: true,
        get() {
          return COEFFICIENT_OF_EXPANSION;
        }
      });
      const Skybox = jsb.Skybox;
      cclegacy.Skybox = Skybox;
      const PostSettings = jsb.PostSettings;
      cclegacy.PostSettings = PostSettings;

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

      const EffectAsset = exports("EffectAsset", jsb.EffectAsset);
      cclegacy.EffectAsset = EffectAsset;
      const effectAssetProto = EffectAsset.prototype;
      effectAssetProto._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this.hideInEditor = false;
      };
      patch_cc_EffectAsset({
        EffectAsset
      });

      const matProto = jsb.Material.prototype;
      function wrapSetProperty(cb, target, name, val, passIdx) {
        if (passIdx != undefined) {
          cb.call(target, name, val, passIdx);
        } else {
          cb.call(target, name, val);
        }
      }
      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 = {}));
      matProto.setProperty = function (name, val, passIdx) {
        if (Array.isArray(val)) {
          const first = val[0];
          if (typeof first === 'number') {
            if (Number.isInteger(first)) {
              wrapSetProperty(this.setPropertyInt32Array, this, name, val, passIdx);
            } else {
              wrapSetProperty(this.setPropertyFloat32Array, this, name, val, passIdx);
            }
          } else if (first instanceof Vec2) {
            wrapSetProperty(this.setPropertyVec2Array, this, name, val, passIdx);
          } else if (first instanceof Vec3) {
            wrapSetProperty(this.setPropertyVec3Array, this, name, val, passIdx);
          } else if (first instanceof Vec4) {
            wrapSetProperty(this.setPropertyVec4Array, this, name, val, passIdx);
          } else if (first instanceof Color$1) {
            wrapSetProperty(this.setPropertyColorArray, this, name, val, passIdx);
          } else if (first instanceof Mat3) {
            wrapSetProperty(this.setPropertyMat3Array, this, name, val, passIdx);
          } else if (first instanceof Mat4) {
            wrapSetProperty(this.setPropertyMat4Array, this, name, val, passIdx);
          } else if (first instanceof Quat) {
            wrapSetProperty(this.setPropertyQuatArray, this, name, val, passIdx);
          } else if (first instanceof TextureBase) {
            wrapSetProperty(this.setPropertyTextureBaseArray, this, name, val, passIdx);
          } else if (first instanceof Texture) {
            wrapSetProperty(this.setPropertyGFXTextureArray, this, name, val, passIdx);
          } else {
            cclegacy.error(`Material.setProperty Unknown type: ${val}`);
          }
        } else if (typeof val === 'number') {
          if (Number.isInteger(val)) {
            wrapSetProperty(this.setPropertyInt32, this, name, val, passIdx);
          } else {
            wrapSetProperty(this.setPropertyFloat32, this, name, val, passIdx);
          }
        } else if (val instanceof Vec2) {
          wrapSetProperty(this.setPropertyVec2, this, name, val, passIdx);
        } else if (val instanceof Vec3) {
          wrapSetProperty(this.setPropertyVec3, this, name, val, passIdx);
        } else if (val instanceof Vec4) {
          wrapSetProperty(this.setPropertyVec4, this, name, val, passIdx);
        } else if (val instanceof Color$1) {
          wrapSetProperty(this.setPropertyColor, this, name, val, passIdx);
        } else if (val instanceof Mat3) {
          wrapSetProperty(this.setPropertyMat3, this, name, val, passIdx);
        } else if (val instanceof Mat4) {
          wrapSetProperty(this.setPropertyMat4, this, name, val, passIdx);
        } else if (val instanceof Quat) {
          wrapSetProperty(this.setPropertyQuat, this, name, val, passIdx);
        } else if (val instanceof TextureBase) {
          wrapSetProperty(this.setPropertyTextureBase, this, name, val, passIdx);
        } else if (val instanceof Texture) {
          wrapSetProperty(this.setPropertyGFXTexture, this, name, val, passIdx);
        } else if (val === null) {
          if (passIdx) {
            this.setPropertyNull(name, passIdx);
          } else {
            this.setPropertyNull(name);
          }
        } else {
          cclegacy.error(`Material.setProperty Unknown type: ${val}`);
        }
      };
      matProto.getProperty = function (name, passIdx) {
        let val;
        if (passIdx !== undefined) {
          val = this._getProperty(name, passIdx);
        } else {
          val = this._getProperty(name);
        }
        if (Array.isArray(val)) {
          const first = val[0];
          const arr = [];
          if (first instanceof jsb.Vec2 || first.type === 0) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Vec2(e.x, e.y));
            }
          } else if (first.type === 1) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Vec3(e.x, e.y, e.z));
            }
          } else if (first.type === 2) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Vec4(e.x, e.y, e.z, e.w));
            }
          } else if (first instanceof jsb.Color) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Color$1(e.r, e.g, e.b, e.a));
            }
          } else if (first.type === 4) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Mat3(e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8]));
            }
          } else if (first.type === 5) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Mat4(e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]));
            }
          } else if (first.type === 3) {
            for (let i = 0, len = val.length; i < len; ++i) {
              const e = val[i];
              arr.push(new Quat(e.x, e.y, e.z, e.w));
            }
          }
          return arr || val;
        } else if (val === null || val === undefined) {
          return null;
        }
        let ret;
        const e = val;
        if (val instanceof jsb.Vec2 || val.type === 0) {
          ret = new Vec3(e.x, e.y);
        } else if (val.type === 1) {
          ret = new Vec3(e.x, e.y, e.z);
        } else if (val.type === 2) {
          ret = new Vec4(e.x, e.y, e.z, e.w);
        } else if (val instanceof jsb.Color) {
          ret = new Color$1(e.r, e.g, e.b, e.a);
        } else if (val.type === 4) {
          ret = new Mat3(e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8]);
        } else if (val.type === 5) {
          ret = new Mat4(e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]);
        } else if (val.type === 3) {
          ret = new Quat(e.x, e.y, e.z, e.w);
        }
        return ret || val;
      };
      const Material$1 = exports("Material", jsb.Material);
      cclegacy.Material = Material$1;
      const materialProto = Material$1.prototype;
      materialProto._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._props = [];
        this._passes = [];
        this._registerPassesUpdatedListener();
        this._isCtorCalled = true;
      };
      const oldOnLoaded = materialProto.onLoaded;
      materialProto.onLoaded = function () {
        this._propsInternal = this._props;
        oldOnLoaded.call(this);
      };
      materialProto._onPassesUpdated = function () {
        this._passes = this.getPasses();
      };
      Object.defineProperty(materialProto, 'passes', {
        enumerable: true,
        configurable: true,
        get() {
          if (!this._isCtorCalled) {
            this._ctor();
            this._passes = this.getPasses();
          }
          return this._passes;
        }
      });
      patch_cc_Material({
        Material: Material$1,
        EffectAsset
      });

      const DEFAULT_WORLD_MIN_POS = exports("DEFAULT_WORLD_MIN_POS", new Vec3(-1024.0, -1024.0, -1024.0));
      const DEFAULT_WORLD_MAX_POS = exports("DEFAULT_WORLD_MAX_POS", new Vec3(1024.0, 1024.0, 1024.0));
      const DEFAULT_OCTREE_DEPTH = exports("DEFAULT_OCTREE_DEPTH", 8);
      const FogType = exports("FogType", Enum({
        LINEAR: 0,
        EXP: 1,
        EXP_SQUARED: 2,
        LAYERED: 3
      }));
      const ShadowSize = exports("ShadowSize", Enum({
        Low_256x256: 256,
        Medium_512x512: 512,
        High_1024x1024: 1024,
        Ultra_2048x2048: 2048
      }));
      const ShadowType$1 = exports("ShadowType", Enum({
        Planar: 0,
        ShadowMap: 1
      }));
      const AmbientInfo = exports("AmbientInfo", jsb.AmbientInfo);
      legacyCC.AmbientInfo = AmbientInfo;
      const SkyboxInfo = exports("SkyboxInfo", jsb.SkyboxInfo);
      legacyCC.SkyboxInfo = SkyboxInfo;
      const FogInfo = exports("FogInfo", jsb.FogInfo);
      legacyCC.FogInfo = FogInfo;
      FogInfo.FogType = FogType;
      const ShadowsInfo = exports("ShadowsInfo", jsb.ShadowsInfo);
      legacyCC.ShadowsInfo = ShadowsInfo;
      const OctreeInfo = exports("OctreeInfo", jsb.OctreeInfo);
      legacyCC.OctreeInfo = OctreeInfo;
      const LightProbeInfo = exports("LightProbeInfo", jsb.LightProbeInfo);
      const SceneGlobals = exports("SceneGlobals", jsb.SceneGlobals);
      legacyCC.SceneGlobals = SceneGlobals;
      const SkinInfo = exports("SkinInfo", jsb.SkinInfo);
      legacyCC.SkinInfo = SkinInfo;
      const PostSettingsInfo = exports("PostSettingsInfo", jsb.PostSettingsInfo);
      legacyCC.PostSettingsInfo = PostSettingsInfo;
      (function () {
        const sceneGlobalsProto = SceneGlobals.prototype;
        sceneGlobalsProto._ctor = function () {
          this._ambientRef = this.getAmbientInfo();
          this._shadowsRef = this.getShadowsInfo();
          this._skyboxRef = this.getSkyboxInfo();
          this._fogRef = this.getFogInfo();
          this._octreeRef = this.getOctreeInfo();
          this._lightProbeRef = this.getLightProbeInfo();
          this._skinRef = this.getSkinInfo();
          this._postSettingsRef = this.getPostSettingsInfo();
        };
        Object.defineProperty(sceneGlobalsProto, 'ambient', {
          enumerable: true,
          configurable: true,
          get() {
            return this._ambientRef;
          },
          set(v) {
            this._ambientRef = v;
            this.setAmbientInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'shadows', {
          enumerable: true,
          configurable: true,
          get() {
            return this._shadowsRef;
          },
          set(v) {
            this._shadowsRef = v;
            this.setShadowsInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, '_skybox', {
          enumerable: true,
          configurable: true,
          get() {
            return this._skyboxRef;
          },
          set(v) {
            this._skyboxRef = v;
            this.setSkyboxInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'skybox', {
          enumerable: true,
          configurable: true,
          get() {
            return this._skyboxRef;
          },
          set(v) {
            this._skyboxRef = v;
            this.setSkyboxInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'fog', {
          enumerable: true,
          configurable: true,
          get() {
            return this._fogRef;
          },
          set(v) {
            this._fogRef = v;
            this.setFogInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'octree', {
          enumerable: true,
          configurable: true,
          get() {
            return this._octreeRef;
          },
          set(v) {
            this._octreeRef = v;
            this.setOctreeInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'lightProbeInfo', {
          enumerable: true,
          configurable: true,
          get() {
            return this._lightProbeRef;
          },
          set(v) {
            this._lightProbeRef = v;
            this.setLightProbeInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'skin', {
          enumerable: true,
          configurable: true,
          get() {
            return this._skinRef;
          },
          set(v) {
            this._skinRef = v;
            this.setSkinInfo(v);
          }
        });
        Object.defineProperty(sceneGlobalsProto, 'postSettings', {
          enumerable: true,
          configurable: true,
          get() {
            return this._postSettingsRef;
          },
          set(v) {
            this._postSettingsRef = v;
            this.setPostSettingsInfo(v);
          }
        });
      })();
      patch_cc_SceneGlobals({
        SceneGlobals,
        AmbientInfo,
        SkyboxInfo,
        FogInfo,
        ShadowsInfo,
        LightProbeInfo,
        OctreeInfo,
        SkinInfo,
        PostSettingsInfo
      });
      patch_cc_OctreeInfo({
        OctreeInfo,
        CCInteger,
        Vec3,
        DEFAULT_WORLD_MAX_POS,
        DEFAULT_WORLD_MIN_POS,
        DEFAULT_OCTREE_DEPTH
      });
      patch_cc_ShadowsInfo({
        ShadowsInfo,
        ShadowType: ShadowType$1,
        CCFloat,
        CCInteger,
        ShadowSize,
        Vec3,
        Color: Color$1,
        Vec2
      });
      patch_cc_FogInfo({
        FogInfo,
        FogType,
        CCFloat,
        Color: Color$1
      });
      patch_cc_SkyboxInfo({
        SkyboxInfo,
        EnvironmentLightingType,
        TextureCube,
        CCFloat,
        Material: Material$1
      });
      patch_cc_AmbientInfo({
        AmbientInfo,
        Vec4,
        Ambient,
        CCFloat,
        legacyCC
      });
      patch_cc_LightProbeInfo({
        LightProbeInfo,
        CCFloat,
        CCInteger
      });
      patch_cc_SkinInfo({
        SkinInfo,
        CCFloat
      });
      patch_cc_PostSettingsInfo({
        PostSettingsInfo,
        ToneMappingType
      });

      var _dec$2j, _class$2j;
      replaceProperty(Node$1.prototype, 'Node', [{
        name: 'childrenCount',
        newName: 'children.length',
        customGetter() {
          return this.children.length;
        }
      }]);
      replaceProperty(Node$1.prototype, 'Node', [{
        name: 'width',
        targetName: 'node.getComponent(UITransform)',
        customGetter() {
          return this._uiProps.uiTransformComp.width;
        },
        customSetter(value) {
          this._uiProps.uiTransformComp.width = value;
        }
      }, {
        name: 'height',
        targetName: 'node.getComponent(UITransform)',
        customGetter() {
          return this._uiProps.uiTransformComp.height;
        },
        customSetter(value) {
          this._uiProps.uiTransformComp.height = value;
        }
      }, {
        name: 'anchorX',
        targetName: 'node.getComponent(UITransform)',
        customGetter() {
          return this._uiProps.uiTransformComp.anchorX;
        },
        customSetter(value) {
          this._uiProps.uiTransformComp.anchorX = value;
        }
      }, {
        name: 'anchorY',
        targetName: 'node.getComponent(UITransform)',
        customGetter() {
          return this._uiProps.uiTransformComp.anchorY;
        },
        customSetter(value) {
          this._uiProps.uiTransformComp.anchorY = value;
        }
      }, {
        name: 'getAnchorPoint',
        targetName: 'node.getComponent(UITransform)',
        customFunction(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._uiProps.uiTransformComp.anchorPoint);
          return out;
        }
      }, {
        name: 'setAnchorPoint',
        targetName: 'node.getComponent(UITransform)',
        customFunction(point, y) {
          this._uiProps.uiTransformComp.setAnchorPoint(point, y);
        }
      }, {
        name: 'getContentSize',
        targetName: 'node.getComponent(UITransform)',
        customFunction(out) {
          if (!out) {
            out = new Size$1();
          }
          out.set(this._uiProps.uiTransformComp.contentSize);
          return out;
        }
      }, {
        name: 'setContentSize',
        targetName: 'node.getComponent(UITransform)',
        customFunction(size, height) {
          if (typeof size === 'number') {
            this._uiProps.uiTransformComp.setContentSize(size, height);
          } else {
            this._uiProps.uiTransformComp.setContentSize(size);
          }
        }
      }]);
      removeProperty(SceneGlobals.prototype, 'SceneGlobals.prototype', [{
        name: 'aspect'
      }, {
        name: 'selfShadow'
      }, {
        name: 'linear'
      }, {
        name: 'packing'
      }, {
        name: 'autoAdapt'
      }, {
        name: 'fixedArea'
      }, {
        name: 'pcf'
      }, {
        name: 'bias'
      }, {
        name: 'normalBias'
      }, {
        name: 'near'
      }, {
        name: 'far'
      }, {
        name: 'shadowDistance'
      }, {
        name: 'invisibleOcclusionRange'
      }, {
        name: 'orthoSize'
      }, {
        name: 'saturation'
      }]);
      replaceProperty(SceneGlobals.prototype, 'SceneGlobals.prototype', [{
        name: 'distance',
        newName: 'planeHeight'
      }, {
        name: 'normal',
        newName: 'planeDirection'
      }, {
        name: 'size',
        newName: 'shadowMapSize'
      }]);
      removeProperty(Node$1.prototype, 'Node.prototype', [{
        name: 'addLayer'
      }, {
        name: 'removeLayer'
      }]);
      replaceProperty(NodeUIProperties.prototype, 'NodeUIProperties', [{
        name: 'opacityDirty',
        newName: 'colorDirty'
      }]);
      removeProperty(Layers, 'Layers', [{
        name: 'All'
      }, {
        name: 'RaycastMask'
      }, {
        name: 'check'
      }]);
      replaceProperty(Layers, 'Layers', [{
        name: 'Default',
        newName: 'DEFAULT',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Always',
        newName: 'ALWAYS',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'IgnoreRaycast',
        newName: 'IGNORE_RAYCAST',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Gizmos',
        newName: 'GIZMOS',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Editor',
        newName: 'EDITOR',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'UI',
        newName: 'UI_3D',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'UI2D',
        newName: 'UI_2D',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'SceneGizmo',
        newName: 'SCENE_GIZMO',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'makeInclusiveMask',
        newName: 'makeMaskInclude',
        target: Layers,
        targetName: 'Layers'
      }, {
        name: 'makeExclusiveMask',
        newName: 'makeMaskExclude',
        target: Layers,
        targetName: 'Layers'
      }]);
      removeProperty(Layers.Enum, 'Layers.Enum', [{
        name: 'ALWAYS'
      }]);
      removeProperty(Layers.BitMask, 'Layers.BitMask', [{
        name: 'ALWAYS'
      }]);
      const HideInHierarchy = CCObject.Flags.HideInHierarchy;
      const DontSave = CCObject.Flags.DontSave;
      let PrivateNode = exports("PrivateNode", (_dec$2j = ccclass$H('cc.PrivateNode'), _dec$2j(_class$2j = class PrivateNode extends Node$1 {
        constructor(name) {
          super(name);
          warnID(12003, this.name);
          this.hideFlags |= DontSave | HideInHierarchy;
        }
      }) || _class$2j));
      replaceProperty(SystemEventType, 'SystemEventType', ['MOUSE_ENTER', 'MOUSE_LEAVE', 'TRANSFORM_CHANGED', 'SCENE_CHANGED_FOR_PERSISTS', 'SIZE_CHANGED', 'ANCHOR_CHANGED', 'COLOR_CHANGED', 'CHILD_ADDED', 'CHILD_REMOVED', 'PARENT_CHANGED', 'NODE_DESTROYED', 'LAYER_CHANGED', 'SIBLING_ORDER_CHANGED'].map(name => ({
        name,
        target: Node$1.EventType,
        targetName: 'Node.EventType'
      })));
      replaceProperty(Node$1.EventType, 'Node.EventType', [{
        name: 'DEVICEMOTION',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }, {
        name: 'KEY_DOWN',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }, {
        name: 'KEY_UP',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      legacyCC.PrivateNode = PrivateNode;

      deprecateModuleExportedName({
        BaseNode: {
          newName: 'Node',
          since: '3.7.0',
          removed: false
        }
      });

      var _dec$2i, _dec2$1z, _class$2i, _class2$1X, _initializer$1P, _dec3$16, _dec4$K, _dec5$E, _dec6$v, _dec7$o, _dec8$f, _class4$q, _class5$o, _initializer2$1n, _initializer3$$, _initializer4$T, _initializer5$F, _initializer6$x, _dec9$c, _class7$6, _class8$5, _initializer7$o, _dec10$6, _dec11$3, _dec12$3, _class10$4, _class11$4, _initializer8$m, _initializer9$k, _initializer10$j, _dec13$2, _dec14$1, _dec15$1, _class13$3, _class14$3, _initializer11$i, _initializer12$h, _dec16, _dec17, _dec18, _class16, _class17$1, _initializer13$e, _initializer14$c, _dec19, _dec20, _dec21, _dec22, _dec23, _dec24, _class19, _class20$2, _initializer15$9, _initializer16$9, _initializer17$6, _initializer18$6, _initializer19$5, _initializer20$5, _dec25, _dec26, _dec27, _dec28, _class22, _class23$1, _initializer21$5, _initializer22$4, _initializer23$3, _initializer24$3, _initializer25$2, _initializer26$2;
      let TargetInfo = (_dec$2i = ccclass$H('cc.TargetInfo'), _dec2$1z = type$a([CCString]), _dec$2i(_class$2i = (_class2$1X = class TargetInfo {
        constructor() {
          this.localID = _initializer$1P && _initializer$1P();
        }
      }, (_initializer$1P = applyDecoratedInitializer(_class2$1X.prototype, "localID", [serializable$l, _dec2$1z], function () {
        return [];
      })), _class2$1X)) || _class$2i);
      let TargetOverrideInfo = (_dec3$16 = ccclass$H('cc.TargetOverrideInfo'), _dec4$K = type$a(CCObject), _dec5$E = type$a(TargetInfo), _dec6$v = type$a([CCString]), _dec7$o = type$a(Node$1), _dec8$f = type$a(TargetInfo), _dec3$16(_class4$q = (_class5$o = class TargetOverrideInfo {
        constructor() {
          this.source = _initializer2$1n && _initializer2$1n();
          this.sourceInfo = _initializer3$$ && _initializer3$$();
          this.propertyPath = _initializer4$T && _initializer4$T();
          this.target = _initializer5$F && _initializer5$F();
          this.targetInfo = _initializer6$x && _initializer6$x();
        }
      }, (_initializer2$1n = applyDecoratedInitializer(_class5$o.prototype, "source", [serializable$l, _dec4$K], function () {
        return null;
      }), _initializer3$$ = applyDecoratedInitializer(_class5$o.prototype, "sourceInfo", [serializable$l, _dec5$E], function () {
        return null;
      }), _initializer4$T = applyDecoratedInitializer(_class5$o.prototype, "propertyPath", [serializable$l, _dec6$v], function () {
        return [];
      }), _initializer5$F = applyDecoratedInitializer(_class5$o.prototype, "target", [serializable$l, _dec7$o], function () {
        return null;
      }), _initializer6$x = applyDecoratedInitializer(_class5$o.prototype, "targetInfo", [serializable$l, _dec8$f], function () {
        return null;
      })), _class5$o)) || _class4$q);
      let CompPrefabInfo = (_dec9$c = ccclass$H('cc.CompPrefabInfo'), _dec9$c(_class7$6 = (_class8$5 = class CompPrefabInfo {
        constructor() {
          this.fileId = _initializer7$o && _initializer7$o();
        }
      }, (_initializer7$o = applyDecoratedInitializer(_class8$5.prototype, "fileId", [serializable$l], function () {
        return '';
      })), _class8$5)) || _class7$6);
      let PropertyOverrideInfo = (_dec10$6 = ccclass$H('CCPropertyOverrideInfo'), _dec11$3 = type$a(TargetInfo), _dec12$3 = type$a([CCString]), _dec10$6(_class10$4 = (_class11$4 = class PropertyOverrideInfo {
        constructor() {
          this.targetInfo = _initializer8$m && _initializer8$m();
          this.propertyPath = _initializer9$k && _initializer9$k();
          this.value = _initializer10$j && _initializer10$j();
        }
        isTarget(localID, propPath) {
        }
      }, (_initializer8$m = applyDecoratedInitializer(_class11$4.prototype, "targetInfo", [serializable$l, _dec11$3], function () {
        return null;
      }), _initializer9$k = applyDecoratedInitializer(_class11$4.prototype, "propertyPath", [serializable$l, _dec12$3], function () {
        return [];
      }), _initializer10$j = applyDecoratedInitializer(_class11$4.prototype, "value", [serializable$l], null)), _class11$4)) || _class10$4);
      let MountedChildrenInfo = (_dec13$2 = ccclass$H('cc.MountedChildrenInfo'), _dec14$1 = type$a(TargetInfo), _dec15$1 = type$a([Node$1]), _dec13$2(_class13$3 = (_class14$3 = class MountedChildrenInfo {
        constructor() {
          this.targetInfo = _initializer11$i && _initializer11$i();
          this.nodes = _initializer12$h && _initializer12$h();
        }
        isTarget(localID) {
        }
      }, (_initializer11$i = applyDecoratedInitializer(_class14$3.prototype, "targetInfo", [serializable$l, _dec14$1], function () {
        return null;
      }), _initializer12$h = applyDecoratedInitializer(_class14$3.prototype, "nodes", [serializable$l, _dec15$1], function () {
        return [];
      })), _class14$3)) || _class13$3);
      let MountedComponentsInfo = (_dec16 = ccclass$H('cc.MountedComponentsInfo'), _dec17 = type$a(TargetInfo), _dec18 = type$a([Component]), _dec16(_class16 = (_class17$1 = class MountedComponentsInfo {
        constructor() {
          this.targetInfo = _initializer13$e && _initializer13$e();
          this.components = _initializer14$c && _initializer14$c();
        }
        isTarget(localID) {
        }
      }, (_initializer13$e = applyDecoratedInitializer(_class17$1.prototype, "targetInfo", [serializable$l, _dec17], function () {
        return null;
      }), _initializer14$c = applyDecoratedInitializer(_class17$1.prototype, "components", [serializable$l, _dec18], function () {
        return [];
      })), _class17$1)) || _class16);
      let PrefabInstance = (_dec19 = ccclass$H('cc.PrefabInstance'), _dec20 = type$a(Node$1), _dec21 = type$a([MountedChildrenInfo]), _dec22 = type$a([MountedComponentsInfo]), _dec23 = type$a([PropertyOverrideInfo]), _dec24 = type$a([TargetInfo]), _dec19(_class19 = (_class20$2 = class PrefabInstance {
        constructor() {
          this.fileId = _initializer15$9 && _initializer15$9();
          this.prefabRootNode = _initializer16$9 && _initializer16$9();
          this.mountedChildren = _initializer17$6 && _initializer17$6();
          this.mountedComponents = _initializer18$6 && _initializer18$6();
          this.propertyOverrides = _initializer19$5 && _initializer19$5();
          this.removedComponents = _initializer20$5 && _initializer20$5();
          this.targetMap = {};
          this.expanded = false;
        }
        findPropertyOverride(localID, propPath) {
        }
        removePropertyOverride(localID, propPath) {
        }
      }, (_initializer15$9 = applyDecoratedInitializer(_class20$2.prototype, "fileId", [serializable$l], function () {
        return '';
      }), _initializer16$9 = applyDecoratedInitializer(_class20$2.prototype, "prefabRootNode", [serializable$l, _dec20], null), _initializer17$6 = applyDecoratedInitializer(_class20$2.prototype, "mountedChildren", [serializable$l, _dec21], function () {
        return [];
      }), _initializer18$6 = applyDecoratedInitializer(_class20$2.prototype, "mountedComponents", [serializable$l, _dec22], function () {
        return [];
      }), _initializer19$5 = applyDecoratedInitializer(_class20$2.prototype, "propertyOverrides", [serializable$l, _dec23], function () {
        return [];
      }), _initializer20$5 = applyDecoratedInitializer(_class20$2.prototype, "removedComponents", [serializable$l, _dec24], function () {
        return [];
      })), _class20$2)) || _class19);
      let PrefabInfo = (_dec25 = ccclass$H('cc.PrefabInfo'), _dec26 = type$a(Node$1), _dec27 = type$a(PrefabInstance), _dec28 = type$a([TargetOverrideInfo]), _dec25(_class22 = (_class23$1 = class PrefabInfo {
        constructor() {
          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$2 && _initializer25$2();
          this.nestedPrefabInstanceRoots = _initializer26$2 && _initializer26$2();
        }
      }, (_initializer21$5 = applyDecoratedInitializer(_class23$1.prototype, "root", [serializable$l, _dec26], null), _initializer22$4 = applyDecoratedInitializer(_class23$1.prototype, "asset", [serializable$l], null), _initializer23$3 = applyDecoratedInitializer(_class23$1.prototype, "fileId", [serializable$l], function () {
        return '';
      }), _initializer24$3 = applyDecoratedInitializer(_class23$1.prototype, "instance", [serializable$l, _dec27], null), _initializer25$2 = applyDecoratedInitializer(_class23$1.prototype, "targetOverrides", [serializable$l, _dec28], null), _initializer26$2 = applyDecoratedInitializer(_class23$1.prototype, "nestedPrefabInstanceRoots", [serializable$l], null)), _class23$1)) || _class22);
      cclegacy._PrefabInfo = PrefabInfo;

      function createNodeWithPrefab(node) {
        const prefabInfo = node === null || node === void 0 ? void 0 : node.prefab;
        if (!prefabInfo) {
          return;
        }
        const prefabInstance = prefabInfo.instance;
        if (!prefabInstance) {
          return;
        }
        if (!prefabInfo.asset) {
          {
            errorID(3701, node.name);
          }
          prefabInfo.instance = undefined;
          return;
        }
        const _objFlags = node._objFlags;
        const _parent = node.getParent();
        const _id = node.uuid;
        node[editorExtrasTag];
        cclegacy.game._isCloning = true;
        {
          prefabInfo.asset._doInstantiate(node);
        }
        cclegacy.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;
        }
        let curTargetMap = targetMap;
        const 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];
        }
        const prefabInfo = node.prefab;
        if (prefabInfo) {
          curTargetMap[prefabInfo.fileId] = node;
        }
        const components = node.components;
        for (let i = 0; i < components.length; i++) {
          const comp = components[i];
          if (comp.__prefab) {
            curTargetMap[comp.__prefab.fileId] = comp;
          }
        }
        for (let i = 0; i < node.children.length; i++) {
          const childNode = node.children[i];
          generateTargetMap(childNode, curTargetMap, false);
        }
      }
      function getTarget(localID, targetMap) {
        if (!localID) {
          return null;
        }
        let target = null;
        let targetIter = targetMap;
        for (let 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 (let i = 0; i < mountedChildren.length; i++) {
          const childInfo = mountedChildren[i];
          if (childInfo && childInfo.targetInfo) {
            const target = getTarget(childInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            let curTargetMap = targetMap;
            const localID = childInfo.targetInfo.localID;
            if (localID.length > 0) {
              for (let i = 0; i < localID.length - 1; i++) {
                curTargetMap = curTargetMap[localID[i]];
              }
            }
            if (childInfo.nodes) {
              for (let i = 0; i < childInfo.nodes.length; i++) {
                const childNode = childInfo.nodes[i];
                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 (let i = 0; i < mountedComponents.length; i++) {
          const componentsInfo = mountedComponents[i];
          if (componentsInfo && componentsInfo.targetInfo) {
            const target = getTarget(componentsInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            if (componentsInfo.components) {
              for (let i = 0; i < componentsInfo.components.length; i++) {
                const comp = componentsInfo.components[i];
                if (!comp) {
                  continue;
                }
                comp.node = target;
                target.getWritableComponents().push(comp);
              }
            }
          }
        }
      }
      function applyRemovedComponents(node, removedComponents, targetMap) {
        if (!removedComponents) {
          return;
        }
        for (let i = 0; i < removedComponents.length; i++) {
          const targetInfo = removedComponents[i];
          if (targetInfo) {
            const target = getTarget(targetInfo.localID, targetMap);
            if (!target || !target.node) {
              continue;
            }
            const 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;
        }
        let target = null;
        for (let i = 0; i < propertyOverrides.length; i++) {
          const propOverride = propertyOverrides[i];
          if (propOverride && propOverride.targetInfo) {
            const targetInfo = propOverride.targetInfo;
            target = getTarget(targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            let targetPropOwner = target;
            const propertyPath = propOverride.propertyPath.slice();
            if (propertyPath.length > 0) {
              const targetPropName = propertyPath.pop();
              if (!targetPropName) {
                continue;
              }
              for (let i = 0; i < propertyPath.length; i++) {
                const propName = propertyPath[i];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              if (Array.isArray(targetPropOwner)) {
                if (targetPropName === 'length') {
                  targetPropOwner[targetPropName] = propOverride.value;
                } else {
                  const 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;
        const targetOverrides = (_node$prefab2 = node.prefab) === null || _node$prefab2 === void 0 ? void 0 : _node$prefab2.targetOverrides;
        if (targetOverrides) {
          for (let i = 0; i < targetOverrides.length; i++) {
            var _targetAsNode$prefab;
            const targetOverride = targetOverrides[i];
            let source = targetOverride.source;
            const sourceInfo = targetOverride.sourceInfo;
            if (sourceInfo) {
              var _src$prefab;
              const src = targetOverride.source;
              const 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;
            }
            let target = null;
            const targetInfo = targetOverride.targetInfo;
            if (!targetInfo) {
              continue;
            }
            const targetAsNode = targetOverride.target;
            const 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;
            }
            const propertyPath = targetOverride.propertyPath.slice();
            let targetPropOwner = source;
            if (propertyPath.length > 0) {
              const targetPropName = propertyPath.pop();
              if (!targetPropName) {
                return;
              }
              for (let i = 0; i < propertyPath.length; i++) {
                const propName = propertyPath[i];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              targetPropOwner[targetPropName] = target;
            }
          }
        }
      }
      function expandPrefabInstanceNode(node, recursively = false) {
        var _node$prefab3;
        const 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(child => {
                expandPrefabInstanceNode(child, true);
              });
            }
          }
          const 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(child => {
              expandPrefabInstanceNode(child, true);
            });
          }
        }
      }
      function expandNestedPrefabInstanceNode(node) {
        const prefabInfo = node.prefab;
        if (prefabInfo && prefabInfo.nestedPrefabInstanceRoots) {
          prefabInfo.nestedPrefabInstanceRoots.forEach(instanceNode => {
            expandPrefabInstanceNode(instanceNode);
          });
        }
      }
      function applyNodeAndComponentId(prefabInstanceNode, rootId) {
        const {
          components,
          children
        } = prefabInstanceNode;
        for (let i = 0; i < components.length; i++) {
          var _comp$__prefab$fileId, _comp$__prefab;
          const comp = components[i];
          const 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 (let i = 0; i < children.length; i++) {
          const child = children[i];
          const prefabInfo = child.prefab;
          const 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 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        CompPrefabInfo: CompPrefabInfo,
        MountedChildrenInfo: MountedChildrenInfo,
        MountedComponentsInfo: MountedComponentsInfo,
        PrefabInfo: PrefabInfo,
        PrefabInstance: PrefabInstance,
        PropertyOverrideInfo: PropertyOverrideInfo,
        TargetInfo: TargetInfo,
        TargetOverrideInfo: TargetOverrideInfo,
        applyMountedChildren: applyMountedChildren,
        applyMountedComponents: applyMountedComponents,
        applyNodeAndComponentId: applyNodeAndComponentId,
        applyPropertyOverrides: applyPropertyOverrides,
        applyRemovedComponents: applyRemovedComponents,
        applyTargetOverrides: applyTargetOverrides,
        createNodeWithPrefab: createNodeWithPrefab,
        expandNestedPrefabInstanceNode: expandNestedPrefabInstanceNode,
        expandPrefabInstanceNode: expandPrefabInstanceNode,
        generateTargetMap: generateTargetMap,
        getTarget: getTarget
      });

      const Scene = exports("Scene", jsb.Scene);
      legacyCC.Scene = Scene;
      const sceneProto = Scene.prototype;
      Object.defineProperty(sceneProto, '_globals', {
        enumerable: true,
        configurable: true,
        get() {
          return this.getSceneGlobals();
        },
        set(v) {
          this._globalRef = v;
          this.setSceneGlobals(v);
        }
      });
      Object.defineProperty(sceneProto, 'globals', {
        enumerable: true,
        configurable: true,
        get() {
          return this.getSceneGlobals();
        }
      });
      Object.defineProperty(sceneProto, '_renderScene', {
        enumerable: true,
        configurable: true,
        get() {
          if (!this._renderSceneInternal) {
            this._renderSceneInternal = this.getRenderScene();
          }
          return this._renderSceneInternal;
        }
      });
      Object.defineProperty(sceneProto, 'renderScene', {
        enumerable: true,
        configurable: true,
        get() {
          if (!this._renderSceneInternal) {
            this._renderSceneInternal = this.getRenderScene();
          }
          return this._renderSceneInternal;
        }
      });
      sceneProto._ctor = function () {
        Node$1.prototype._ctor.apply(this, arguments);
        this._inited = false;
        this._renderSceneInternal = null;
        this._globalRef = null;
        this._prefabSyncedInLiveReload = false;
      };
      sceneProto._onBatchCreated = function (dontSyncChildPrefab) {
        if (this._parent) {
          this._siblingIndex = this._parent.children.indexOf(this);
        }
        const children = this._children;
        const len = children.length;
        let child;
        for (let i = 0; i < len; ++i) {
          child = children[i];
          child._siblingIndex = i;
          child._onBatchCreated(dontSyncChildPrefab);
        }
      };
      const oldLoad = sceneProto._load;
      sceneProto._load = function () {
        this._scene = this;
        if (!this._inited) {
          expandNestedPrefabInstanceNode(this);
          applyTargetOverrides(this);
          this._onBatchCreated(EDITOR);
          this._inited = true;
        }
        updateChildrenForDeserialize(this);
        oldLoad.call(this);
      };
      sceneProto._activate = function (active) {
        active = active !== false;
        legacyCC.director._nodeActivator.activateNode(this, active);
        {
          this._globals.activate(this);
          if (this._renderScene) {
            this._renderScene.activate();
          }
        }
      };
      sceneProto._instantiate = function () {};
      patch_cc_Scene({
        Scene,
        SceneGlobals
      });

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

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

      const MAX_POOL_SIZE = 4;
      const IsPreloadStarted = CCObject.Flags.IsPreloadStarted;
      const IsOnLoadStarted = CCObject.Flags.IsOnLoadStarted;
      const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
      const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
      const Deactivating = CCObject.Flags.Deactivating;
      class UnsortedInvoker extends LifeCycleInvoker {
        add(comp) {
          this._zero.array.push(comp);
        }
        remove(comp) {
          this._zero.fastRemove(comp);
        }
        cancelInactive(flagToClear) {
          LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear);
        }
        invoke() {
          this._invoke(this._zero);
          this._zero.array.length = 0;
        }
      }
      const invokePreload = createInvokeImplJit('c.__preload();') ;
      const invokeOnLoad = createInvokeImplJit(`c.onLoad();c._objFlags|=${IsOnLoadCalled}`, false, IsOnLoadCalled) ;
      const activateTasksPool = new Pool$1(MAX_POOL_SIZE);
      activateTasksPool.get = function getActivateTask() {
        const task = this._get() || {
          preload: new UnsortedInvoker(invokePreload),
          onLoad: new OneOffInvoker(invokeOnLoad),
          onEnable: new OneOffInvoker(invokeOnEnable)
        };
        task.preload.zero.i = -1;
        let 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);
        }
      }
      class NodeActivator {
        constructor() {
          this.reset();
        }
        reset() {
          this._activatingStack = [];
        }
        activateNode(node, active) {
          if (active) {
            const 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);
            const stack = this._activatingStack;
            for (const lastTask of stack) {
              lastTask.preload.cancelInactive(IsPreloadStarted);
              lastTask.onLoad.cancelInactive(IsOnLoadStarted);
              lastTask.onEnable.cancelInactive(IsOnEnableCalled);
            }
          }
          node.emit("active-in-hierarchy-changed", node);
        }
        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));
            }
            const deactivatedOnLoading = !comp.node.activeInHierarchy;
            if (deactivatedOnLoading) {
              return;
            }
            legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker);
          }
        }
        destroyComp(comp) {
          legacyCC.director._compScheduler.disableComp(comp);
          if (comp.internalOnDestroy && comp._objFlags & IsOnLoadCalled) {
            comp.internalOnDestroy();
          }
        }
        _activateNodeRecursively(node, preloadInvoker, onLoadInvoker, onEnableInvoker) {
          if (node._objFlags & Deactivating) {
            errorID(3816, node.name);
            return;
          }
          node._setActiveInHierarchy(true);
          let originCount = node.components.length;
          for (let i = 0; i < originCount; ++i) {
            const component = node.components[i];
            if (component instanceof legacyCC.Component) {
              this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker);
            } else {
              _componentCorrupted(node, component, i);
              --i;
              --originCount;
            }
          }
          for (let i = 0, len = node.children.length; i < len; ++i) {
            const child = node.children[i];
            if (child.active) {
              this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker);
            }
          }
          node._onPostActivated(true);
        }
        _deactivateNodeRecursively(node) {
          node._objFlags |= Deactivating;
          node._setActiveInHierarchy(false);
          const originCount = node.components.length;
          for (let c = 0; c < originCount; ++c) {
            const component = node.components[c];
            if (component._enabled) {
              legacyCC.director._compScheduler.disableComp(component);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          for (let i = 0, len = node.children.length; i < len; ++i) {
            const child = node.children[i];
            if (child.activeInHierarchy) {
              this._deactivateNodeRecursively(child);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          node._onPostActivated(false);
          node._objFlags &= ~Deactivating;
        }
      } exports("NodeActivator", NodeActivator);

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

      var _dec$2h, _class$2h, _class2$1W, _initializer$1O, _initializer2$1m, _initializer3$_, _class3$C;
      const OptimizationPolicy = Enum({
        AUTO: 0,
        SINGLE_INSTANCE: 1,
        MULTI_INSTANCE: 2
      });
      let Prefab = exports("Prefab", (_dec$2h = ccclass$H('cc.Prefab'), _dec$2h(_class$2h = (_class2$1W = (_class3$C = class Prefab extends Asset {
        constructor() {
          super();
          this.data = _initializer$1O && _initializer$1O();
          this.optimizationPolicy = _initializer2$1m && _initializer2$1m();
          this.persistent = _initializer3$_ && _initializer3$_();
          this._createFunction = null;
          this._instantiatedTimes = 0;
        }
        createNode(cb) {
          const node = legacyCC.instantiate(this);
          node.name = this.name;
          cb(null, node);
        }
        compileCreateFunction() {
          {
            this._createFunction = compile(this.data);
          }
        }
        _doInstantiate(rootToRedirect) {
          if (!this.data._prefab) {
            warnID(3700);
          }
          if (!this._createFunction) {
            this.compileCreateFunction();
          }
          return this._createFunction(rootToRedirect);
        }
        _instantiate() {
          let node;
          let 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;
        }
        initDefault(uuid) {
          super.initDefault(uuid);
          this.data = new Node$1();
          this.data.name = '(Missing Node)';
          const prefabInfo = new legacyCC._PrefabInfo();
          prefabInfo.asset = this;
          prefabInfo.root = this.data;
          this.data._prefab = prefabInfo;
        }
        validate() {
          return !!this.data;
        }
        onLoaded() {
          const rootNode = this.data;
          expandNestedPrefabInstanceNode(rootNode);
          applyTargetOverrides(rootNode);
          {
            updateChildrenForDeserialize(rootNode);
          }
        }
      }, _class3$C.OptimizationPolicy = OptimizationPolicy, _class3$C.OptimizationPolicyThreshold = 3, _class3$C), (_initializer$1O = applyDecoratedInitializer(_class2$1W.prototype, "data", [serializable$l], function () {
        return null;
      }), _initializer2$1m = applyDecoratedInitializer(_class2$1W.prototype, "optimizationPolicy", [serializable$l], function () {
        return OptimizationPolicy.AUTO;
      }), _initializer3$_ = applyDecoratedInitializer(_class2$1W.prototype, "persistent", [serializable$l], function () {
        return false;
      })), _class2$1W)) || _class$2h));
      value(Prefab, '_utils', utils);
      legacyCC.Prefab = Prefab;
      {
        obsolete(legacyCC, 'cc._Prefab', 'Prefab');
      }

      class UIRendererManager {
        constructor() {
          this._allRenderers = [];
          this._dirtyRenderers = [];
          this._dirtyVersion = 0;
        }
        addRenderer(uiRenderer) {
          if (uiRenderer._internalId === -1) {
            uiRenderer._internalId = this._allRenderers.length;
            this._allRenderers.push(uiRenderer);
          }
        }
        removeRenderer(uiRenderer) {
          if (uiRenderer._internalId !== -1) {
            {
              assert(this._allRenderers[uiRenderer._internalId] === uiRenderer);
            }
            const 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;
            }
          }
        }
        markDirtyRenderer(uiRenderer) {
          if (uiRenderer._dirtyVersion !== this._dirtyVersion && uiRenderer._internalId !== -1) {
            this._dirtyRenderers.push(uiRenderer);
            uiRenderer._dirtyVersion = this._dirtyVersion;
          }
        }
        updateAllDirtyRenderers() {
          const dirtyRenderers = this._dirtyRenderers;
          for (let i = 0; i < this._dirtyRenderers.length; i++) {
            {
              assert(dirtyRenderers[i]._internalId !== -1);
            }
            dirtyRenderers[i].updateRenderer();
          }
          this._dirtyRenderers.length = 0;
          this._dirtyVersion++;
        }
      }
      const uiRendererManager = new UIRendererManager();

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

      function visitAsset(asset, deps) {
        if (!asset._uuid) {
          return;
        }
        deps.push(asset._uuid);
      }
      function visitComponent(comp, deps) {
        const props = Object.getOwnPropertyNames(comp);
        for (let i = 0; i < props.length; i++) {
          const propName = props[i];
          if (propName === 'node' || propName === '__eventTargets') {
            continue;
          }
          const value = comp[propName];
          if (typeof value === 'object' && value) {
            if (Array.isArray(value)) {
              for (let j = 0; j < value.length; j++) {
                const val = value[j];
                if (val instanceof Asset) {
                  visitAsset(val, deps);
                }
              }
            } else if (!value.constructor || value.constructor === Object) {
              const keys = Object.getOwnPropertyNames(value);
              for (let j = 0; j < keys.length; j++) {
                const 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 (let i = 0; i < node._components.length; i++) {
          visitComponent(node._components[i], deps);
        }
        for (let i = 0; i < node._children.length; i++) {
          visitNode$1(node._children[i], deps);
        }
      }
      function descendOpRef(asset, refs, exclude, op) {
        exclude.push(asset._uuid);
        const depends = dependUtil.getDeps(asset._uuid);
        for (let i = 0, l = depends.length; i < l; i++) {
          const dependAsset = assets.get(depends[i]);
          if (!dependAsset) {
            continue;
          }
          const 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);
        }
      }
      const _temp = [];
      function checkCircularReference(asset) {
        const 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 (const uuid in refs) {
          if (refs[uuid] !== 0) {
            descendOpRef(assets.get(uuid), refs, _temp, 1);
          }
        }
        _temp.length = 0;
        return refs[asset._uuid];
      }
      class ReleaseManager {
        constructor() {
          this._persistNodeDeps = new Cache();
          this._toDelete = new Cache();
          this._eventListener = false;
          this._dontDestroyAssets = [];
        }
        addIgnoredAsset(asset) {
          this._dontDestroyAssets.push(asset._uuid);
        }
        init() {
          this._persistNodeDeps.clear();
          this._toDelete.clear();
        }
        _addPersistNodeRef(node) {
          const deps = [];
          visitNode$1(node, deps);
          for (let i = 0, l = deps.length; i < l; i++) {
            const dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.addRef();
            }
          }
          this._persistNodeDeps.add(node.uuid, deps);
        }
        _removePersistNodeRef(node) {
          if (!this._persistNodeDeps.has(node.uuid)) {
            return;
          }
          const deps = this._persistNodeDeps.get(node.uuid);
          for (let i = 0, l = deps.length; i < l; i++) {
            const dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.decRef();
            }
          }
          this._persistNodeDeps.remove(node.uuid);
        }
        _autoRelease(oldScene, newScene, persistNodes) {
          if (oldScene) {
            const childs = dependUtil.getDeps(oldScene.uuid);
            for (let i = 0, l = childs.length; i < l; i++) {
              const asset = assets.get(childs[i]);
              if (asset) {
                asset.decRef(oldScene.autoReleaseAssets);
              }
            }
            const dependencies = dependUtil._depends.get(oldScene.uuid);
            if (dependencies && dependencies.persistDeps) {
              const persistDeps = dependencies.persistDeps;
              for (let i = 0, l = persistDeps.length; i < l; i++) {
                const asset = assets.get(persistDeps[i]);
                if (asset) {
                  asset.decRef(oldScene.autoReleaseAssets);
                }
              }
            }
            if (oldScene.uuid !== newScene.uuid) {
              dependUtil.remove(oldScene.uuid);
            }
          }
          const sceneDeps = dependUtil._depends.get(newScene.uuid);
          if (sceneDeps) {
            sceneDeps.persistDeps = [];
          }
          for (const key in persistNodes) {
            const node = persistNodes[key];
            const deps = this._persistNodeDeps.get(node.uuid);
            for (const dep of deps) {
              const dependAsset = assets.get(dep);
              if (dependAsset) {
                dependAsset.addRef();
              }
            }
            if (!sceneDeps) {
              continue;
            }
            sceneDeps.persistDeps.push(...deps);
          }
        }
        tryRelease(asset, 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));
          }
        }
        _freeAssets() {
          this._eventListener = false;
          this._toDelete.forEach(asset => {
            this._free(asset);
          });
          this._toDelete.clear();
        }
        _free(asset, force = false) {
          const 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);
          const depends = dependUtil.getDeps(uuid);
          for (let i = 0, l = depends.length; i < l; i++) {
            const dependAsset = assets.get(depends[i]);
            if (dependAsset) {
              dependAsset.decRef(false);
              {
                this._free(dependAsset, false);
              }
            }
          }
          {
            asset.destroy();
          }
          dependUtil.remove(uuid);
        }
      }
      const releaseManager = new ReleaseManager();

      let defaultProgressCallback = null;
      function setDefaultProgressCallback(onProgress) {
        defaultProgressCallback = onProgress;
      }
      function clear(task, clearRef) {
        for (let i = 0, l = task.input.length; i < l; i++) {
          const item = task.input[i];
          {
            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 = 0) {
        process(index, (err, result) => {
          index++;
          if (!err || index > times) {
            if (onComplete) {
              onComplete(err, result);
            }
          } else {
            setTimeout(() => {
              retry(process, times, wait, onComplete, index);
            }, wait);
          }
        });
      }
      function getDepends(uuid, data, exclude, depends, config) {
        try {
          const info = dependUtil.parse(uuid, data);
          for (let i = 0, l = info.deps.length; i < l; i++) {
            const 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({
              ...info.nativeDep
            });
          }
        } catch (e) {
          error(e.message, e.stack);
        }
      }
      function cache(id, asset, cacheAsset) {
        if (!asset) {
          return;
        }
        cacheAsset = cacheAsset !== undefined ? cacheAsset : cclegacy.assetManager.cacheAsset;
        if (!isScene(asset) && cacheAsset && !asset.isDefault) {
          assets.add(id, asset);
        }
      }
      function setProperties(uuid, asset, assetsMap) {
        let missingAsset = false;
        const depends = dependMap.get(asset);
        if (depends) {
          for (let i = 0, l = depends.length; i < l; i++) {
            const depend = depends[i];
            const dependAsset = assetsMap[`${depend.uuid}@import`];
            if (!dependAsset) {
              {
                errorID(16350, depend.uuid);
              }
              cclegacy.assetManager.dispatchAssetMissing(asset, depend.owner, depend.prop, depend.uuid);
              if (depend.type && depend.type !== Asset) {
                const placeHolder = new depend.type();
                placeHolder.initDefault(depend.uuid);
                depend.owner[depend.prop] = placeHolder;
              }
              missingAsset = true;
            } else {
              depend.owner[depend.prop] = dependAsset.addRef();
            }
          }
          dependMap.delete(asset);
        }
        if (nativeDependMap.has(asset)) {
          if (assetsMap[`${uuid}@native`]) {
            asset._nativeAsset = assetsMap[`${uuid}@native`];
          } else {
            missingAsset = true;
            errorID(16351, uuid);
          }
          nativeDependMap.delete(asset);
        }
        return missingAsset;
      }
      function gatherAsset(task) {
        const source = task.source;
        if (!task.options.__outputAsArray__ && source.length === 1) {
          task.output = source[0].content;
        } else {
          const output = task.output = [];
          for (let i = 0, l = source.length; i < l; i++) {
            output.push(source[i].content);
          }
        }
      }
      function forEach(array, process, onComplete) {
        let count = 0;
        const errs = [];
        const length = array.length;
        if (length === 0 && onComplete) {
          onComplete(errs);
        }
        const cb = err => {
          if (err) {
            errs.push(err);
          }
          count++;
          if (count === length) {
            if (onComplete) {
              onComplete(errs);
            }
          }
        };
        for (let i = 0; i < length; i++) {
          process(array[i], cb);
        }
      }
      function parseParameters(options, onProgress, onComplete) {
        let optionsOut = options;
        let onProgressOut = onProgress;
        let onCompleteOut = onComplete;
        if (onComplete === undefined) {
          const 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) {
        let typeOut = type;
        let onProgressOut = onProgress;
        let onCompleteOut = onComplete;
        if (onComplete === undefined) {
          const 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 = {}) {
        const item = map[uuid];
        if (!item || checked[uuid]) {
          return false;
        }
        checked[uuid] = true;
        let result = false;
        const deps = dependUtil.getDeps(uuid);
        if (deps) {
          for (let i = 0, l = deps.length; i < l; i++) {
            const dep = deps[i];
            if (dep === owner || checkCircleReference(owner, dep, map, checked)) {
              result = true;
              break;
            }
          }
        }
        return result;
      }
      function asyncify(cb) {
        return (p1, p2) => {
          if (!cb) {
            return;
          }
          const refs = [];
          if (Array.isArray(p2)) {
            p2.forEach(x => x instanceof Asset && refs.push(x.addRef()));
          } else if (p2 instanceof Asset) {
            refs.push(p2.addRef());
          }
          callInNextTick(() => {
            refs.forEach(x => x.decRef(false));
            cb(p1, p2);
          });
        };
      }

      class Bundle {
        constructor() {
          this._config = new Config();
        }
        get config() {
          return this._config;
        }
        get name() {
          return this._config.name;
        }
        get deps() {
          return this._config.deps;
        }
        get base() {
          return this._config.base;
        }
        getInfoWithPath(path, type) {
          return this._config.getInfoWithPath(path, type);
        }
        getDirWithPath(path, type, out) {
          return this._config.getDirWithPath(path, type, out);
        }
        getAssetInfo(uuid) {
          return this._config.getAssetInfo(uuid);
        }
        getSceneInfo(name) {
          return this._config.getSceneInfo(name);
        }
        init(options) {
          this._config.init(options);
          bundles.add(options.name, this);
        }
        load(paths, type, onProgress, onComplete) {
          const {
            type: _type,
            onProgress: onProg,
            onComplete: onComp
          } = parseLoadResArgs(type, onProgress, onComplete);
          const options = {
            __requestType__: "path",
            type: _type,
            bundle: this.name,
            __outputAsArray__: Array.isArray(paths)
          };
          cclegacy.assetManager.loadAny(paths, options, onProg, onComp);
        }
        preload(paths, type, onProgress, onComplete) {
          const {
            type: _type,
            onProgress: onProg,
            onComplete: onComp
          } = parseLoadResArgs(type, onProgress, onComplete);
          cclegacy.assetManager.preloadAny(paths, {
            __requestType__: "path",
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        }
        loadDir(dir, type, onProgress, onComplete) {
          const {
            type: _type,
            onProgress: onProg,
            onComplete: onComp
          } = parseLoadResArgs(type, onProgress, onComplete);
          cclegacy.assetManager.loadAny(dir, {
            __requestType__: "dir",
            type: _type,
            bundle: this.name,
            __outputAsArray__: true
          }, onProg, onComp);
        }
        preloadDir(dir, type, onProgress, onComplete) {
          const {
            type: _type,
            onProgress: onProg,
            onComplete: onComp
          } = parseLoadResArgs(type, onProgress, onComplete);
          cclegacy.assetManager.preloadAny(dir, {
            __requestType__: "dir",
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        }
        loadScene(sceneName, options, onProgress, onComplete) {
          const {
            options: opts,
            onProgress: onProg,
            onComplete: onComp
          } = parseParameters(options, onProgress, onComplete);
          opts.preset = opts.preset || 'scene';
          opts.bundle = this.name;
          cclegacy.assetManager.loadAny({
            scene: sceneName
          }, opts, onProg, (err, sceneAsset) => {
            if (err) {
              error(err.message, err.stack);
            } else if (sceneAsset.scene) {
              const 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);
            }
          });
        }
        preloadScene(sceneName, options, onProgress, onComplete) {
          const {
            options: opts,
            onProgress: onProg,
            onComplete: onComp
          } = parseParameters(options, onProgress, onComplete);
          opts.bundle = this.name;
          cclegacy.assetManager.preloadAny({
            scene: sceneName
          }, opts, onProg, err => {
            if (err) {
              errorID(1210, sceneName, err.message);
            }
            if (onComp) {
              onComp(err);
            }
          });
        }
        get(path, type) {
          const info = this.getInfoWithPath(path, type);
          if (info) {
            return assets.get(info.uuid) || null;
          }
          return null;
        }
        release(path, type) {
          const asset = this.get(path, type);
          if (asset) {
            releaseManager.tryRelease(asset, true);
          }
        }
        releaseUnusedAssets() {
          assets.forEach(asset => {
            const info = this.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset);
            }
          });
        }
        releaseAll() {
          assets.forEach(asset => {
            const info = this.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset, true);
            }
          });
        }
        _destroy() {
          this._config.destroy();
        }
      }
      const resources = exports("resources", new Bundle());
      cclegacy.resources = resources;

      class CacheManager {
        constructor() {
          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) {
        const img = new ccwindow$1.Image();
        if (ccwindow$1.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) {
        const xhr = new XMLHttpRequest();
        const 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 (const header in options.xhrHeader) {
            xhr.setRequestHeader(header, options.xhrHeader[header]);
          }
        }
        xhr.onload = () => {
          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 = e => {
            if (e.lengthComputable) {
              onProgress(e.loaded, e.total);
            }
          };
        }
        xhr.onerror = () => {
          if (onComplete) {
            onComplete(new Error(`${errInfo}${xhr.status}(error)`));
          }
        };
        xhr.ontimeout = () => {
          if (onComplete) {
            onComplete(new Error(`${errInfo}${xhr.status}(time out)`));
          }
        };
        xhr.onabort = () => {
          if (onComplete) {
            onComplete(new Error(`${errInfo}${xhr.status}(abort)`));
          }
        };
        xhr.send(null);
        return xhr;
      }

      const ccdocument$5 = ccwindow$1.document;
      const downloaded = {};
      function downloadScript(url, options, onComplete) {
        if (downloaded[url]) {
          if (onComplete) {
            onComplete(null);
          }
          return null;
        }
        const script = ccdocument$5.createElement('script');
        if (ccwindow$1.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$5.body.appendChild(script);
        return script;
      }

      const REGEX = /^(?:\w+:\/\/|\.+\/).+/;
      const downloadImage = (url, options, onComplete) => {
        const func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && cclegacy.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage;
        func(url, options, onComplete);
      };
      const downloadBlob = (url, options, onComplete) => {
        options.xhrResponseType = 'blob';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      const downloadJson = (url, options, onComplete) => {
        options.xhrResponseType = 'json';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      const downloadArrayBuffer = (url, options, onComplete) => {
        options.xhrResponseType = 'arraybuffer';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      const downloadCCON = (url, options, onComplete) => {
        downloader._downloadJson(url, options, (err, json) => {
          if (err) {
            onComplete(err);
            return;
          }
          const cconPreface = parseCCONJson(json);
          const chunkPromises = Promise.all(cconPreface.chunks.map(chunk => new Promise((resolve, reject) => {
            downloader._downloadArrayBuffer(`${mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => {
              if (err) {
                reject(err);
              } else {
                resolve(new Uint8Array(chunkBuffer));
              }
            });
          })));
          chunkPromises.then(chunks => {
            const ccon = new CCON(cconPreface.document, chunks);
            onComplete(null, ccon);
          }).catch(err => {
            onComplete(err);
          });
        });
      };
      const downloadCCONB = (url, options, onComplete) => {
        downloader._downloadArrayBuffer(url, options, (err, arrayBuffer) => {
          if (err) {
            onComplete(err);
            return;
          }
          try {
            const ccon = decodeCCONBinary(new Uint8Array(arrayBuffer));
            onComplete(null, ccon);
          } catch (err) {
            onComplete(err);
          }
        });
      };
      const downloadText = (url, options, onComplete) => {
        options.xhrResponseType = 'text';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      const downloadBundle = (nameOrUrl, options, onComplete) => {
        const bundleName = basename(nameOrUrl);
        let url = nameOrUrl;
        if (!REGEX.test(url)) {
          if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
            url = `${downloader.remoteServerAddress}remote/${bundleName}`;
          } else {
            url = `assets/${bundleName}`;
          }
        }
        const version = options.version || downloader.bundleVers[bundleName];
        let count = 0;
        const config = `${url}/config.${version ? `${version}.` : ''}json`;
        let out = null;
        let error = null;
        downloadJson(config, options, (err, response) => {
          error = err || error;
          out = response;
          if (out) {
            out.base = `${url}/`;
          }
          if (++count === 2) {
            onComplete(error, out);
          }
        });
        const jspath = `${url}/index.${version ? `${version}.` : ''}js`;
        downloadScript(jspath, options, err => {
          error = err || error;
          if (++count === 2) {
            onComplete(error, out);
          }
        });
      };
      class Downloader {
        static get instance() {
          if (!Downloader._instance) {
            Downloader._instance = new Downloader();
          }
          return Downloader._instance;
        }
        get remoteServerAddress() {
          return this._remoteServerAddress;
        }
        init(remoteServerAddress = '', bundleVers = {}, remoteBundles = []) {
          this._downloading.clear();
          this._queue.length = 0;
          this._remoteServerAddress = remoteServerAddress;
          this.bundleVers = bundleVers;
          this.remoteBundles = remoteBundles;
        }
        get handlers() {
          return this._downloaders;
        }
        register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._downloaders, type);
          } else {
            this._downloaders[type] = handler;
          }
        }
        download(id, url, type, options, onComplete) {
          const file = files.get(id);
          if (file) {
            onComplete(null, file);
            return;
          }
          const downloadCallbacks = this._downloading.get(id);
          if (downloadCallbacks) {
            downloadCallbacks.push(onComplete);
            const request = this._queue.find(x => x.id === id);
            if (!request) {
              return;
            }
            const priority = options.priority || 0;
            if (request.priority < priority) {
              request.priority = priority;
              this._queueDirty = true;
            }
            return;
          }
          const maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount : this.maxRetryCount;
          const maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency : this.maxConcurrency;
          const maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame;
          const handler = this._downloaders[type] || this._downloaders.default;
          const process = (index, callback) => {
            if (index === 0) {
              this._downloading.add(id, [onComplete]);
            }
            if (!this.limited) {
              handler(urlAppendTimestamp(url, this.appendTimeStamp), options, callback);
              return;
            }
            this._updateTime();
            const 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,
                priority: options.priority || 0,
                url,
                options,
                done,
                handler
              });
              this._queueDirty = true;
              if (this._totalNum < maxConcurrency) {
                this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              }
            }
          };
          const finale = (err, result) => {
            if (!err) {
              files.add(id, result);
            }
            const callbacks = this._downloading.remove(id);
            for (let i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          };
          retry(process, maxRetryCount, this.retryInterval, finale);
        }
        loadSubpackage(name, completeCallback) {
          cclegacy.assetManager.loadBundle(name, null, completeCallback);
        }
        constructor() {
          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;
        }
        _updateTime() {
          const now = performance.now();
          const deltaTime = cclegacy.game.deltaTime;
          const interval = deltaTime > this._maxInterval ? this._maxInterval : deltaTime;
          if (now - this._lastDate > interval * 1000) {
            this._totalNumThisPeriod = 0;
            this._lastDate = now;
          }
        }
        _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((a, b) => a.priority - b.priority);
              this._queueDirty = false;
            }
            const 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);
        }
        _handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame) {
          if (!this._checkNextPeriod && this._queue.length > 0) {
            callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame);
            this._checkNextPeriod = true;
          }
        }
      }
      Downloader._instance = void 0;
      const downloader = Downloader.instance;
      var downloader$1 = Downloader.instance;

      var _dec$2g, _class$2g, _class2$1V, _initializer$1N;
      let JsonAsset = exports("JsonAsset", (_dec$2g = ccclass$H('cc.JsonAsset'), _dec$2g(_class$2g = (_class2$1V = class JsonAsset extends Asset {
        constructor() {
          super();
          this.json = _initializer$1N && _initializer$1N();
        }
      }, (_initializer$1N = applyDecoratedInitializer(_class2$1V.prototype, "json", [serializable$l], function () {
        return null;
      })), _class2$1V)) || _class$2g));
      cclegacy.JsonAsset = JsonAsset;

      var _dec$2f, _class$2f, _class2$1U, _initializer$1M;
      let TextAsset = exports("TextAsset", (_dec$2f = ccclass$H('cc.TextAsset'), _dec$2f(_class$2f = (_class2$1U = class TextAsset extends Asset {
        toString() {
          return this.text;
        }
        constructor() {
          super();
          this.text = _initializer$1M && _initializer$1M();
        }
      }, (_initializer$1M = applyDecoratedInitializer(_class2$1U.prototype, "text", [serializable$l], function () {
        return '';
      })), _class2$1U)) || _class$2f));
      cclegacy.TextAsset = TextAsset;

      const BufferAsset = exports("BufferAsset", jsb.BufferAsset);
      cclegacy.BufferAsset = jsb.BufferAsset;
      patch_cc_BufferAsset({
        BufferAsset
      });

      function createImageAsset(id, data, options, onComplete) {
        let out = null;
        let err = null;
        try {
          out = new ImageAsset$1();
          out._nativeUrl = id;
          out._nativeAsset = data;
        } catch (e) {
          err = e;
        }
        onComplete(err, out);
      }
      function createJsonAsset(id, data, options, onComplete) {
        const out = new JsonAsset();
        out.json = data;
        onComplete(null, out);
      }
      function createTextAsset(id, data, options, onComplete) {
        const out = new TextAsset();
        out.text = data;
        onComplete(null, out);
      }
      function createBufferAsset(id, data, options, onComplete) {
        const out = new BufferAsset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createAsset(id, data, options, onComplete) {
        const out = new Asset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createBundle(id, data, options, onComplete) {
        let bundle = bundles.get(data.name);
        if (!bundle) {
          bundle = data.name === "resources" ? resources : new Bundle();
          data.base = data.base || `${id}/`;
          bundle.init(data);
        }
        {
          module.import(`virtual:///prerequisite-imports/${bundle.name}`).then(() => {
            onComplete(null, bundle);
          }).catch(onComplete);
        }
      }
      class Factory {
        constructor() {
          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,
            '.astc': 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
          };
        }
        register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._producers, type);
          } else {
            this._producers[type] = handler;
          }
        }
        create(id, data, type, options, onComplete) {
          const handler = this._producers[type] || this._producers.default;
          const asset = assets.get(id);
          if (!options.reloadAsset && asset) {
            onComplete(null, asset);
            return;
          }
          const creating = this._creating.get(id);
          if (creating) {
            creating.push(onComplete);
            return;
          }
          this._creating.add(id, [onComplete]);
          handler(id, data, options, (err, result) => {
            if (!err && result instanceof Asset) {
              result._uuid = id;
              cache(id, result, options.cacheAsset);
            }
            const callbacks = this._creating.remove(id);
            for (let i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          });
        }
      }
      var factory = new Factory();

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

      function fetch(task, done) {
        let firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        const {
          options,
          progress
        } = task;
        const depends = [];
        const total = progress.total;
        const exclude = options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, (item, cb) => {
          if (!item.isNative && assets.has(item.uuid)) {
            const 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, (err, data) => {
            if (err) {
              if (!task.isFinished) {
                if (!cclegacy.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();
          });
        }, () => {
          if (task.isFinished) {
            clear(task);
            task.dispatch('error');
            return;
          }
          if (depends.length > 0) {
            const subTask = Task.create({
              input: depends,
              progress,
              options,
              onProgress: task.onProgress,
              onError: Task.prototype.recycle,
              onComplete: err => {
                if (!err) {
                  task.output.push(...subTask.output);
                  subTask.recycle();
                }
                if (firstTask) {
                  decreaseRef(task);
                }
                done(err);
              }
            });
            fetchPipeline.async(subTask);
            return;
          }
          if (firstTask) {
            decreaseRef(task);
          }
          done();
        });
      }
      function decreaseRef(task) {
        const output = task.output;
        for (let i = 0, l = output.length; i < l; i++) {
          if (output[i].content) {
            output[i].content.decRef(false);
          }
        }
      }

      class SAXParser {
        constructor() {
          this._parser = null;
          if (globalThis.DOMParser) {
            this._parser = new DOMParser();
          }
        }
        parse(xmlTxt) {
          return this._parseXML(xmlTxt);
        }
        _parseXML(textxml) {
          if (this._parser) {
            return this._parser.parseFromString(textxml, 'text/xml');
          }
          throw new Error('Dom parser is not supported in this platform!');
        }
      }
      class PlistParser extends SAXParser {
        parse(xmlTxt) {
          const xmlDoc = this._parseXML(xmlTxt);
          const plist = xmlDoc.documentElement;
          if (plist.tagName !== 'plist') {
            warnID(5100);
            return {};
          }
          let node = null;
          for (let i = 0, len = plist.childNodes.length; i < len; i++) {
            node = plist.childNodes[i];
            if (node.nodeType === 1) {
              break;
            }
          }
          return this._parseNode(node);
        }
        _parseNode(node) {
          let data = null;
          const 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 (let 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;
        }
        _parseArray(node) {
          const data = [];
          for (let i = 0, len = node.childNodes.length; i < len; i++) {
            const child = node.childNodes[i];
            if (child.nodeType !== 1) {
              continue;
            }
            data.push(this._parseNode(child));
          }
          return data;
        }
        _parseDict(node) {
          const data = {};
          let key = '';
          for (let i = 0, len = node.childNodes.length; i < len; i++) {
            const 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;
        }
      }
      const plistParser = new PlistParser();

      class Parser {
        static get instance() {
          if (!this._instance) {
            this._instance = new Parser();
          }
          return this._instance;
        }
        constructor() {
          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
          };
        }
        parseImage(file, options, onComplete) {
          if (file instanceof HTMLImageElement) {
            onComplete(null, file);
            return;
          }
          createImageBitmap(file, {
            premultiplyAlpha: 'none'
          }).then(result => {
            onComplete(null, result);
          }, err => {
            onComplete(err, null);
          });
        }
        parsePVRTex(file, options, onComplete) {
          let err = null;
          let out = null;
          try {
            out = ImageAsset$1.parseCompressedTextures(file, 0);
          } catch (e) {
            err = e;
            warn(err);
          }
          onComplete(err, out);
        }
        parsePKMTex(file, options, onComplete) {
          let err = null;
          let out = null;
          try {
            out = ImageAsset$1.parseCompressedTextures(file, 1);
          } catch (e) {
            err = e;
            warn(err);
          }
          onComplete(err, out);
        }
        parseASTCTex(file, options, onComplete) {
          let err = null;
          let out = null;
          try {
            out = ImageAsset$1.parseCompressedTextures(file, 2);
          } catch (e) {
            err = e;
            warn(err);
          }
          onComplete(err, out);
        }
        parsePlist(file, options, onComplete) {
          let err = null;
          const result = plistParser.parse(file);
          if (!result) {
            err = new Error('parse failed');
          }
          onComplete(err, result);
        }
        parseImport(file, options, onComplete) {
          if (!file) {
            onComplete(new Error(`The json file of asset ${options.__uuid__} is empty or missing`));
            return;
          }
          let result = null;
          let err = null;
          try {
            result = deserializeAsset(file, options);
          } catch (e) {
            err = e;
          }
          onComplete(err, result);
        }
        init() {
          this._parsing.clear();
        }
        register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._parsers, type);
          } else {
            this._parsers[type] = handler;
          }
        }
        parse(id, file, type, options, onComplete) {
          const parsedAsset = parsed.get(id);
          if (parsedAsset) {
            onComplete(null, parsedAsset);
            return;
          }
          const parsing = this._parsing.get(id);
          if (parsing) {
            parsing.push(onComplete);
            return;
          }
          const parseHandler = this._parsers[type];
          if (!parseHandler) {
            onComplete(null, file);
            return;
          }
          this._parsing.add(id, [onComplete]);
          parseHandler(file, options, (err, data) => {
            if (err) {
              files.remove(id);
            } else if (!isScene(data)) {
              parsed.add(id, data);
            }
            const callbacks = this._parsing.remove(id);
            for (let i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, data);
            }
          });
        }
      }
      Parser._instance = void 0;
      var parser = Parser.instance;

      function load(task, done) {
        let firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        const {
          options,
          progress
        } = task;
        options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, (item, cb) => {
          const subTask = Task.create({
            input: item,
            onProgress: task.onProgress,
            options,
            progress,
            onComplete: (err, result) => {
              if (err && !task.isFinished) {
                if (!cclegacy.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);
        }, () => {
          options.__exclude__ = null;
          if (task.isFinished) {
            clear(task);
            task.dispatch('error');
            return;
          }
          gatherAsset(task);
          clear(task);
          done();
        });
      }
      const loadOneAssetPipeline = new Pipeline('loadOneAsset', [function fetch(task, done) {
        const item = task.output = task.input;
        const {
          options,
          isNative,
          uuid,
          file
        } = item;
        const {
          reloadAsset
        } = options;
        if (file || !reloadAsset && !isNative && assets.has(uuid)) {
          done();
          return;
        }
        packManager.load(item, task.options, (err, data) => {
          item.file = data;
          done(err);
        });
      }, function parse(task, done) {
        const item = task.output = task.input;
        const progress = task.progress;
        const exclude = task.options.__exclude__;
        const {
          id,
          file,
          options
        } = item;
        if (item.isNative) {
          parser.parse(id, file, item.ext, options, (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 {
          const {
            uuid
          } = item;
          if (uuid in exclude) {
            const {
              finish,
              content,
              err,
              callbacks
            } = exclude[uuid];
            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,
                item
              });
            }
          } else if (!options.reloadAsset && assets.has(uuid)) {
            const 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, (err, asset) => {
              if (err) {
                done(err);
                return;
              }
              loadDepends(task, asset, done);
            });
          }
        }
      }]);
      function loadDepends(task, asset, done) {
        const {
          input: item,
          progress
        } = task;
        const {
          uuid,
          id,
          options,
          config
        } = item;
        const {
          cacheAsset
        } = options;
        const 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);
        }
        const repeatItem = task.options.__exclude__[uuid] = {
          content: asset,
          finish: false,
          callbacks: [{
            done,
            item
          }]
        };
        const subTask = Task.create({
          input: depends,
          options: task.options,
          onProgress: task.onProgress,
          onError: Task.prototype.recycle,
          progress,
          onComplete: err => {
            if (asset.decRef) {
              asset.decRef(false);
            }
            repeatItem.finish = true;
            repeatItem.err = err;
            if (!err) {
              const output = Array.isArray(subTask.output) ? subTask.output : [subTask.output];
              const map = Object.create(null);
              for (const dependAsset of output) {
                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) {
                errorID(16352, uuid, e.message, e.stack);
              }
              files.remove(id);
              parsed.remove(id);
              cache(uuid, asset, cacheAsset);
              subTask.recycle();
            }
            const callbacks = repeatItem.callbacks;
            for (let i = 0, l = callbacks.length; i < l; i++) {
              const 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) {
        const options = task.options;
        const subOptions = Object.create(null);
        const leftOptions = Object.create(null);
        for (const op in options) {
          switch (op) {
            case "path":
            case "uuid":
            case "dir":
            case "scene":
            case "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;
        const subTask = Task.create({
          input: task.input,
          options: subOptions
        });
        let err = null;
        try {
          task.output = task.source = transformPipeline.sync(subTask);
        } catch (e) {
          err = e;
          for (let i = 0, l = subTask.output.length; i < l; i++) {
            subTask.output[i].recycle();
          }
        }
        subTask.recycle();
        done(err);
      }

      class RequestItem {
        constructor() {
          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 = '';
        }
        get id() {
          if (!this._id) {
            this._id = `${this.overrideUuid || this.uuid}@${this.isNative ? 'native' : 'import'}`;
          }
          return this._id;
        }
        static create() {
          let out;
          if (RequestItem._deadPool.length !== 0) {
            out = RequestItem._deadPool.pop();
          } else {
            out = new RequestItem();
          }
          return out;
        }
        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);
        }
      }
      RequestItem.MAX_DEAD_NUM = 500;
      RequestItem._deadPool = [];

      const infos = [];
      function parse(task) {
        var _info2;
        const options = task.options;
        const input = Array.isArray(task.input) ? task.input : [task.input];
        task.output = [];
        for (let i = 0; i < input.length; i++) {
          let item = input[i];
          let out = RequestItem.create();
          let config = null;
          let info = null;
          if (typeof item === 'string') {
            item = Object.create(null);
            item[options.__requestType__ || "uuid"] = input[i];
          }
          if (typeof item === 'object') {
            addon(item, options);
            if (item.preset) {
              addon(item, presets[item.preset]);
            }
            for (const key in item) {
              switch (key) {
                case "uuid":
                  {
                    var _info;
                    const uuid = out.uuid = decodeUuid(item.uuid);
                    if (!item.bundle) {
                      const bundle = bundles.find(bundle => !!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 "dir":
                  if (bundles.has(item.bundle)) {
                    bundles.get(item.bundle).config.getDirWithPath(item.dir, item.type, infos);
                    for (const assetInfo of infos) {
                      input.push({
                        uuid: assetInfo.uuid,
                        __isNative__: false,
                        ext: assetInfo.extension || '.json',
                        bundle: item.bundle
                      });
                    }
                    infos.length = 0;
                  }
                  out.recycle();
                  out = null;
                  break;
                case "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 "scene":
                  if (!item.bundle) {
                    const bundle = bundles.find(bundle => !!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 "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) {
                break;
              }
            }
          }
          if (!out) {
            continue;
          }
          task.output.push(out);
          if (!out.uuid && !out.url) {
            throw new Error(`Can not parse this input:${JSON.stringify(item)}`);
          }
        }
        return null;
      }
      function replaceOverrideAsset(task) {
        const input = task.output = task.input;
        for (let i = 0; i < input.length; i++) {
          const item = input[i];
          if (assetsOverrideMap.has(item.uuid)) {
            const uuid = assetsOverrideMap.get(item.uuid);
            const bundle = bundles.find(bundle => !!bundle.getAssetInfo(uuid));
            if (bundle) {
              var _info3;
              item.overrideUuid = uuid;
              let config = bundle.config;
              let 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);
            }
          }
        }
      }
      function combine(task) {
        const input = task.output = task.input;
        for (let i = 0; i < input.length; i++) {
          const item = input[i];
          if (item.url) {
            continue;
          }
          let url = '';
          let base = '';
          const config = item.config;
          if (item.isNative) {
            base = config && config.nativeBase ? config.base + config.nativeBase : cclegacy.assetManager.generalNativeBase;
          } else {
            base = config && config.importBase ? config.base + config.importBase : cclegacy.assetManager.generalImportBase;
          }
          const uuid = item.overrideUuid || item.uuid;
          let 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;
      }

      const EVENT_ASSET_MISSING = 'asset-missing';
      class AssetManager {
        static get instance() {
          if (!this._instance) {
            this._instance = new AssetManager();
          }
          return this._instance;
        }
        constructor() {
          this.pipeline = pipeline.append(preprocess).append(load);
          this.fetchPipeline = fetchPipeline.append(preprocess).append(fetch);
          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;
          this.loadPipe = load;
          this.references = references;
          this._releaseManager = releaseManager;
          this._files = files;
          this._parsed = parsed;
          this._parsePipeline = null ;
          this._projectBundles = [];
          this._eventTarget = new EventTarget();
        }
        get files() {
          return this._files;
        }
        getReleaseManager() {
          return this._releaseManager;
        }
        get main() {
          return bundles.get("main") || null;
        }
        get resources() {
          return bundles.get("resources") || null;
        }
        onAssetMissing(func, target) {
          this._eventTarget.on(EVENT_ASSET_MISSING, func, target);
        }
        offAssetMissing(func, target) {
          this._eventTarget.off(EVENT_ASSET_MISSING, func, target);
        }
        dispatchAssetMissing(parentAsset, owner, propName, uuid) {
          this._eventTarget.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid);
        }
        init(options = {}) {
          const server = options.server || settings.querySettings("assets", 'server') || '';
          const bundleVers = options.bundleVers || settings.querySettings("assets", 'bundleVers') || {};
          const remoteBundles = options.remoteBundles || settings.querySettings("assets", 'remoteBundles') || [];
          const downloadMaxConcurrency = options.downloadMaxConcurrency || settings.querySettings("assets", 'downloadMaxConcurrency');
          if (downloadMaxConcurrency && downloadMaxConcurrency > 0) {
            this.downloader.maxConcurrency = downloadMaxConcurrency;
          }
          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();
          let importBase = options.importBase || settings.querySettings("assets", 'importBase') || '';
          if (importBase && importBase.endsWith('/')) {
            importBase = importBase.substr(0, importBase.length - 1);
          }
          let nativeBase = options.nativeBase || settings.querySettings("assets", 'nativeBase') || '';
          if (nativeBase && nativeBase.endsWith('/')) {
            nativeBase = nativeBase.substr(0, nativeBase.length - 1);
          }
          this.generalImportBase = importBase;
          this.generalNativeBase = nativeBase;
          this._projectBundles = settings.querySettings("assets", 'projectBundles') || [];
          const assetsOverride = settings.querySettings("assets", 'assetsOverrides') || {};
          for (const key in assetsOverride) {
            this.assetsOverrideMap.set(key, assetsOverride[key]);
          }
        }
        getBundle(name) {
          return bundles.get(name) || null;
        }
        removeBundle(bundle) {
          bundle._destroy();
          bundles.remove(bundle.name);
        }
        loadAny(requests, options, onProgress, onComplete) {
          const {
            options: opts,
            onProgress: onProg,
            onComplete: onComp
          } = parseParameters(options, onProgress, onComplete);
          opts.preset = opts.preset || 'default';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          const task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          pipeline.async(task);
        }
        preloadAny(requests, options, onProgress, onComplete) {
          const {
            options: opts,
            onProgress: onProg,
            onComplete: onComp
          } = parseParameters(options, onProgress, onComplete);
          opts.preset = opts.preset || 'preload';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          const task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          fetchPipeline.async(task);
        }
        loadRemote(url, options, onComplete) {
          const {
            options: opts,
            onComplete: onComp
          } = parseParameters(options, undefined, 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
          }, opts, null, (err, data) => {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(url, data, opts.ext || extname(url), opts, (p1, p2) => {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        }
        loadBundle(nameOrUrl, options, onComplete) {
          const {
            options: opts,
            onComplete: onComp
          } = parseParameters(options, undefined, onComplete);
          const 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, (err, data) => {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(nameOrUrl, data, 'bundle', opts, (p1, p2) => {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        }
        releaseAsset(asset) {
          releaseManager.tryRelease(asset, true);
        }
        releaseUnusedAssets() {
          assets.forEach(asset => {
            releaseManager.tryRelease(asset);
          });
        }
        releaseAll() {
          assets.forEach(asset => {
            releaseManager.tryRelease(asset, true);
          });
        }
        loadWithJson(json, options, onProgress, onComplete) {
          {
            throw new Error('Only valid in Editor');
          }
        }
      } exports("AssetManager", 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;
      AssetManager.DependUtil = DependUtil;
      const assetManager = exports("assetManager", cclegacy.assetManager = AssetManager.instance);
      cclegacy.AssetManager = AssetManager;

      const ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc'];
      const AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a'];
      function GetTrue() {
        return true;
      }
      const md5Pipe = {
        transformURL(url) {
          const uuid = getUuidFromURL(url);
          if (!uuid) {
            return url;
          }
          const bundle = bundles.find(b => !!b.getAssetInfo(uuid));
          if (!bundle) {
            return url;
          }
          let hashValue = '';
          const info = bundle.getAssetInfo(uuid);
          if (url.startsWith(bundle.base + bundle.config.nativeBase)) {
            hashValue = info.nativeVer || '';
          } else {
            hashValue = info.ver || '';
          }
          if (!hashValue || url.indexOf(hashValue) !== -1) {
            return url;
          }
          let hashPatchInFolder = false;
          if (extname(url) === '.ttf') {
            hashPatchInFolder = true;
          }
          if (hashPatchInFolder) {
            const dirname$1 = dirname(url);
            const basename$1 = basename(url);
            url = `${dirname$1}.${hashValue}/${basename$1}`;
          } else {
            url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,})/, (match, uuid) => `${match}.${hashValue}`);
          }
          return url;
        }
      };
      class CCLoader {
        constructor() {
          this._autoReleaseSetting = Object.create(null);
          this._parseLoadResArgs = parseLoadResArgs;
        }
        set onProgress(val) {
          setDefaultProgressCallback(val);
        }
        get _cache() {
          if (assets instanceof Cache) {
            return assets.map;
          } else {
            const map = {};
            assets.forEach((val, key) => {
              map[key] = val;
            });
            return map;
          }
        }
        load(res, progressCallback, completeCallback) {
          if (completeCallback === undefined) {
            if (progressCallback !== undefined) {
              completeCallback = progressCallback;
              progressCallback = null;
            }
          }
          const requests = Array.isArray(res) ? res : [res];
          for (let i = 0; i < requests.length; i++) {
            const item = requests[i];
            if (typeof item === 'string') {
              requests[i] = {
                url: item,
                __isNative__: true
              };
            } else {
              if (item.type) {
                item.ext = `.${item.type}`;
                item.type = undefined;
              }
              if (item.url) {
                item.__isNative__ = true;
              }
            }
          }
          const images = [];
          const audios = [];
          assetManager.loadAny(requests, null, (finish, total, item) => {
            if (item.content) {
              if (ImageFmts.includes(item.ext)) {
                images.push(item.content);
              } else if (AudioFmts.includes(item.ext)) {
                audios.push(item.content);
              }
            }
            if (progressCallback) {
              progressCallback(finish, total, item);
            }
          }, (err, native) => {
            let out = null;
            if (!err) {
              native = Array.isArray(native) ? native : [native];
              for (let i = 0; i < native.length; i++) {
                const item = native[i];
                if (!(item instanceof Asset)) {
                  let asset = item;
                  const url = requests[i].url;
                  if (images.includes(asset)) {
                    factory.create(url, item, '.png', {}, (err, image) => {
                      asset = native[i] = image;
                    });
                  } else if (audios.includes(asset)) {
                    factory.create(url, item, '.mp3', {}, (err, audio) => {
                      asset = native[i] = audio;
                    });
                  }
                  assets.add(url, asset);
                }
              }
              if (native.length > 1) {
                const map = Object.create(null);
                native.forEach(asset => {
                  map[asset._uuid] = asset;
                });
                out = {
                  isCompleted: GetTrue,
                  _map: map
                };
              } else {
                out = native[0];
              }
            }
            if (completeCallback) {
              completeCallback(err, out);
            }
          });
        }
        getXMLHttpRequest() {
          return new XMLHttpRequest();
        }
        getItem(id) {
          return assetManager.assets.has(id) ? {
            content: assetManager.assets.get(id)
          } : null;
        }
        loadRes(url, type, progressCallback, completeCallback) {
          const {
            type: _type,
            onProgress,
            onComplete
          } = this._parseLoadResArgs(type, progressCallback, completeCallback);
          const extname$1 = extname(url);
          if (extname$1 && !resources.getInfoWithPath(url, _type)) {
            url = url.slice(0, -extname$1.length);
          }
          resources.load(url, _type, onProgress, onComplete);
        }
        loadResArray(urls, type, progressCallback, completeCallback) {
          const {
            type: _type,
            onProgress,
            onComplete
          } = this._parseLoadResArgs(type, progressCallback, completeCallback);
          urls.forEach((url, i) => {
            const extname$1 = extname(url);
            if (extname$1 && !resources.getInfoWithPath(url, _type)) {
              urls[i] = url.slice(0, -extname$1.length);
            }
          });
          resources.load(urls, _type, onProgress, onComplete);
        }
        loadResDir(url, type, progressCallback, completeCallback) {
          const {
            type: _type,
            onProgress,
            onComplete
          } = this._parseLoadResArgs(type, progressCallback, completeCallback);
          resources.loadDir(url, _type, onProgress, (err, out) => {
            let urls = [];
            if (!err) {
              const infos = resources.getDirWithPath(url, _type);
              urls = infos.map(info => info.path);
            }
            if (onComplete) {
              onComplete(err, out, urls);
            }
          });
        }
        getRes(url, type) {
          return assets.has(url) ? assets.get(url) : resources.get(url, type);
        }
        getResCount() {
          return assets.count;
        }
        getDependsRecursively(owner) {
          if (!owner) {
            return [];
          }
          const uuid = typeof owner === 'string' ? owner : owner._uuid;
          return dependUtil.getDepsRecursively(uuid).concat([uuid]);
        }
        get md5Pipe() {
          return md5Pipe;
        }
        get downloader() {
          return downloader$1;
        }
        get loader() {
          return assetManager.parser;
        }
        addDownloadHandlers(extMap) {
          const handler = Object.create(null);
          for (const type in extMap) {
            const func = extMap[type];
            handler[`.${type}`] = (url, options, onComplete) => {
              func({
                url
              }, onComplete);
            };
          }
          downloader$1.register(handler);
        }
        addLoadHandlers(extMap) {
          const handler = Object.create(null);
          for (const type in extMap) {
            const func = extMap[type];
            handler[`.${type}`] = (file, options, onComplete) => {
              func({
                content: file
              }, onComplete);
            };
          }
          parser.register(handler);
        }
        release(asset) {
          if (Array.isArray(asset)) {
            for (let i = 0; i < asset.length; i++) {
              let key = asset[i];
              if (typeof key === 'string') {
                key = assets.get(key);
              }
              assetManager.releaseAsset(key);
            }
          } else if (asset) {
            if (typeof asset === 'string') {
              asset = assets.get(asset);
            }
            assetManager.releaseAsset(asset);
          }
        }
        releaseAsset(asset) {
          assetManager.releaseAsset(asset);
        }
        releaseRes(res, type) {
          resources.release(res, type);
        }
        releaseAll() {
          assetManager.releaseAll();
          assets.clear();
        }
        removeItem(id) {
          return !!assets.remove(id);
        }
        setAutoRelease(asset, autoRelease) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          this._autoReleaseSetting[asset] = !!autoRelease;
        }
        setAutoReleaseRecursively(asset, autoRelease) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          autoRelease = !!autoRelease;
          this._autoReleaseSetting[asset] = autoRelease;
          const depends = dependUtil.getDepsRecursively(asset);
          for (let i = 0; i < depends.length; i++) {
            this._autoReleaseSetting[depends[i]] = autoRelease;
          }
        }
        isAutoRelease(asset) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          return !!this._autoReleaseSetting[asset];
        }
      } exports("CCLoader", CCLoader);
      const loader = exports("loader", new CCLoader());
      const AssetLibrary = exports("AssetLibrary", {
        init(options) {
          options.importBase = options.libraryPath;
          options.nativeBase = options.rawAssetsBase ;
          assetManager.init(options);
          if (options.rawAssets) {
            resources.init({
              base: '',
              deps: [],
              scenes: {},
              redirect: [],
              debug: true,
              packs: {},
              types: [],
              versions: {
                import: [],
                native: []
              },
              name: "resources",
              importBase: options.importBase,
              nativeBase: options.nativeBase,
              paths: options.rawAssets.assets,
              uuids: Object.keys(options.rawAssets.assets),
              extensionMap: {}
            });
          }
        },
        loadAsset(uuid, callback, options) {
          assetManager.loadAny(uuid, callback);
        }
      });
      const url = exports("url", {});
      replaceProperty(url, 'url', [{
        name: 'normalize',
        target: assetManager.utils,
        targetName: 'assetManager.utils',
        newName: 'normalize'
      }, {
        name: 'raw',
        targetName: 'Asset.prototype',
        newName: 'nativeUrl',
        customFunction: url => {
          if (url.startsWith('resources/')) {
            return transform({
              path: changeExtname(url.substr(10)),
              bundle: "resources",
              __isNative__: true,
              ext: extname(url)
            });
          }
          return '';
        }
      }]);
      removeProperty(AssetLibrary, 'AssetLibrary', [{
        name: 'getLibUrlNoExt',
        suggest: 'AssetLibrary.getLibUrlNoExt was removed, if you want to transform url, please use assetManager.utils.getUrlWithUuid instead'
      }, {
        name: 'queryAssetInfo',
        suggest: 'AssetLibrary.queryAssetInfo was removed'
      }]);
      removeProperty(loader, 'loader', [{
        name: 'releaseResDir',
        suggest: 'loader.releaseResDir was removed, please use assetManager.releaseAsset instead'
      }, {
        name: 'flowInDeps',
        suggest: 'loader.flowInDeps was removed'
      }, {
        name: 'assetLoader',
        suggest: 'loader.assetLoader was removed, assetLoader and md5Pipe were merged into assetManager.transformPipeline'
      }]);
      replaceProperty(cclegacy, 'cc', [{
        name: 'loader',
        newName: 'assetManager',
        logTimes: 1,
        customGetter: () => loader
      }, {
        name: 'AssetLibrary',
        newName: 'assetManager',
        logTimes: 1,
        customGetter: () => AssetLibrary
      }, {
        name: 'Pipeline',
        target: AssetManager,
        targetName: 'AssetManager',
        newName: 'Pipeline',
        logTimes: 1
      }, {
        name: 'url',
        targetName: 'assetManager',
        newName: 'utils',
        logTimes: 1,
        customGetter: () => url
      }]);
      removeProperty(cclegacy, 'cc', [{
        name: 'LoadingItems',
        suggest: getError(1400, 'LoadingItems', 'AssetManager.Task')
      }]);
      replaceProperty(macro, 'macro', [{
        name: 'DOWNLOAD_MAX_CONCURRENT',
        target: downloader$1,
        targetName: 'assetManager.downloader',
        newName: 'maxConcurrency'
      }]);
      const _autoRelease = releaseManager._autoRelease;
      releaseManager._autoRelease = function (oldScene, newScene, persistNodes) {
        _autoRelease.call(releaseManager, oldScene, newScene, persistNodes);
        const releaseSettings = loader._autoReleaseSetting;
        const keys = Object.keys(releaseSettings);
        for (let i = 0; i < keys.length; i++) {
          const key = keys[i];
          if (releaseSettings[key] === true) {
            const asset = assets.get(key);
            if (asset) {
              releaseManager.tryRelease(asset);
            }
          }
        }
      };

      const Texture2D = jsb.Texture2D;
      const ImageAsset = jsb.ImageAsset;
      const BuiltinResMgr = jsb.BuiltinResMgr;
      const builtinResMgrProto = BuiltinResMgr.prototype;
      builtinResMgrProto.init = function () {
        this._resources = {};
        this._materialsToBeCompiled = [];
        const resources = this._resources;
        const len = 2;
        const numChannels = 4;
        const blackValueView = new Uint8Array(len * len * numChannels);
        for (let i = 0; i < len * len; i++) {
          const offset = i * numChannels;
          blackValueView[offset] = 0;
          blackValueView[offset + 1] = 0;
          blackValueView[offset + 2] = 0;
          blackValueView[offset + 3] = 255;
        }
        const blackMemImageSource = {
          width: len,
          height: len,
          _data: blackValueView,
          _compressed: false,
          format: 35
        };
        const imgAsset = new ImageAsset(blackMemImageSource);
        const blackTexture = new Texture2D();
        blackTexture._uuid = 'black-texture';
        blackTexture.image = imgAsset;
        resources[blackTexture._uuid] = blackTexture;
        if (cclegacy.SpriteFrame) {
          const spriteFrame = new cclegacy.SpriteFrame();
          const image = imgAsset;
          const texture = new Texture2D();
          texture.image = image;
          spriteFrame.texture = texture;
          spriteFrame._uuid = 'default-spriteframe';
          resources[spriteFrame._uuid] = spriteFrame;
        }
        this.initBuiltinRes();
      };
      builtinResMgrProto.get = function (uuid) {
        const res = this._resources[uuid];
        return res || this.getAsset(uuid);
      };
      builtinResMgrProto.compileBuiltinMaterial = function () {
        for (let i = 0; i < this._materialsToBeCompiled.length; ++i) {
          const mat = this._materialsToBeCompiled[i];
          for (let j = 0; j < mat.passes.length; ++j) {
            mat.passes[j].tryCompile();
          }
        }
        this._materialsToBeCompiled.length = 0;
      };
      builtinResMgrProto.loadBuiltinAssets = function () {
        const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets');
        if (!builtinAssets) return Promise.resolve();
        const resources = this._resources;
        return new Promise((resolve, reject) => {
          assetManager.loadBundle("internal", (err, bundle) => {
            if (err) {
              reject(err);
              return;
            }
            assetManager.loadAny(builtinAssets, (err, assets) => {
              if (err) {
                reject(err);
              } else {
                assets.forEach(asset => {
                  resources[asset.name] = asset;
                  asset.nativeUrl;
                  releaseManager.addIgnoredAsset(asset);
                  this.addAsset(asset.name, asset);
                  if (asset instanceof cclegacy.Material) {
                    this._materialsToBeCompiled.push(asset);
                  }
                });
                resolve();
              }
            });
          });
        });
      };
      const builtinResMgr = exports("builtinResMgr", cclegacy.builtinResMgr = BuiltinResMgr.getInstance());

      const DirectorEvent = exports("DirectorEvent", {
        "INIT": "director_init",
        "RESET": "director_reset",
        "BEFORE_SCENE_LOADING": "director_before_scene_loading",
        "BEFORE_SCENE_LAUNCH": "director_before_scene_launch",
        "AFTER_SCENE_LAUNCH": "director_after_scene_launch",
        "BEFORE_UPDATE": "director_before_update",
        "AFTER_UPDATE": "director_after_update",
        "BEFORE_DRAW": "director_before_draw",
        "AFTER_DRAW": "director_after_draw",
        "BEFORE_COMMIT": "director_before_commit",
        "BEFORE_RENDER": "director_before_render",
        "AFTER_RENDER": "director_after_render",
        "BEFORE_PHYSICS": "director_before_physics",
        "AFTER_PHYSICS": "director_after_physics",
        "BEGIN_FRAME": "director_begin_frame",
        "END_FRAME": "director_end_frame"
      });
      class Director extends EventTarget {
        constructor() {
          super();
          this._compScheduler = new ComponentScheduler();
          this._nodeActivator = new NodeActivator();
          this._invalid = false;
          this._paused = false;
          this._root = null;
          this._loadingScene = '';
          this._scene = null;
          this._totalFrames = 0;
          this._scheduler = new Scheduler();
          this._systems = [];
          this._persistRootNodes = {};
        }
        end() {
          this.once("director_end_frame", () => {
            this.purgeDirector();
          });
        }
        pause() {
          this._paused = true;
        }
        purgeDirector() {
          this._scheduler.unscheduleAll();
          this._compScheduler.unscheduleAll();
          this._nodeActivator.reset();
          {
            if (isValid(this._scene)) {
              this._scene.destroy();
            }
            this._scene = null;
          }
          this.stopAnimation();
          assetManager.releaseAll();
        }
        reset() {
          var _this$getScene;
          this.purgeDirector();
          for (const 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_reset");
          this.startAnimation();
        }
        runSceneImmediate(scene, onBeforeLoadScene, onLaunched) {
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(scene instanceof Scene, 1216);
          {
            console.time('InitScene');
          }
          scene._load();
          {
            console.timeEnd('InitScene');
          }
          {
            console.time('AttachPersist');
          }
          const persistNodeList = Object.keys(this._persistRootNodes).map(x => this._persistRootNodes[x]);
          for (let i = 0; i < persistNodeList.length; i++) {
            const node = persistNodeList[i];
            node.emit("scene-changed-for-persists", scene.renderScene);
            const existNode = scene.uuid === node._originalSceneId && scene.getChildByUuid(node.uuid);
            if (existNode) {
              const 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');
          }
          const 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_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_after_scene_launch", scene);
        }
        runScene(scene, onBeforeLoadScene, onLaunched) {
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(Boolean(scene), 1205);
          assertID(scene instanceof Scene, 1216);
          this.once("director_end_frame", () => {
            this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched);
          });
        }
        loadScene(sceneName, onLaunched, onUnloaded) {
          if (this._loadingScene) {
            warnID(1208, sceneName, this._loadingScene);
            return false;
          }
          const bundle = assetManager.bundles.find(bundle => !!bundle.getSceneInfo(sceneName));
          if (bundle) {
            this.emit("director_before_scene_loading", sceneName);
            this._loadingScene = sceneName;
            console.time(`LoadScene ${sceneName}`);
            bundle.loadScene(sceneName, (err, scene) => {
              console.timeEnd(`LoadScene ${sceneName}`);
              this._loadingScene = '';
              if (err) {
                error(err);
                if (onLaunched) {
                  onLaunched(err);
                }
              } else {
                this.runSceneImmediate(scene, onUnloaded, onLaunched);
              }
            });
            return true;
          } else {
            errorID(1209, sceneName);
            return false;
          }
        }
        preloadScene(sceneName, onProgress, onLoaded) {
          const bundle = assetManager.bundles.find(bundle => !!bundle.getSceneInfo(sceneName));
          if (bundle) {
            bundle.preloadScene(sceneName, null, onProgress, onLoaded);
          } else {
            const err = `Can not preload the scene "${sceneName}" because it is not in the build settings.`;
            if (onLoaded) {
              onLoaded(new Error(err));
            }
            error(`preloadScene: ${err}`);
          }
        }
        resume() {
          this._paused = false;
        }
        get root() {
          return this._root;
        }
        getScene() {
          return this._scene;
        }
        getDeltaTime() {
          return cclegacy.game.deltaTime;
        }
        getTotalTime() {
          return cclegacy.game.totalTime;
        }
        getCurrentTime() {
          return cclegacy.game.frameStartTime;
        }
        getTotalFrames() {
          return this._totalFrames;
        }
        isPaused() {
          return this._paused;
        }
        getScheduler() {
          return this._scheduler;
        }
        setScheduler(scheduler) {
          if (this._scheduler !== scheduler) {
            this.unregisterSystem(this._scheduler);
            this._scheduler = scheduler;
            this.registerSystem(Scheduler.ID, scheduler, 200);
          }
        }
        registerSystem(name, sys, priority) {
          sys.id = name;
          sys.priority = priority;
          this._systems.push(sys);
          this._systems.sort(System.sortByPriority);
        }
        unregisterSystem(sys) {
          fastRemove(this._systems, sys);
          this._systems.sort(System.sortByPriority);
        }
        getSystem(name) {
          return this._systems.find(sys => sys.id === name);
        }
        getAnimationManager() {
          return this.getSystem(cclegacy.AnimationManager.ID);
        }
        startAnimation() {
          this._invalid = false;
        }
        stopAnimation() {
          this._invalid = true;
        }
        mainLoop(now) {
          let dt;
          {
            dt = cclegacy.game._calculateDT(false);
          }
          this.tick(dt);
        }
        tick(dt) {
          if (!this._invalid) {
            this.emit("director_begin_frame");
            {
              input$1._frameDispatchEvents();
            }
            if (!this._paused) {
              this.emit("director_before_update");
              this._compScheduler.startPhase();
              this._compScheduler.updatePhase(dt);
              for (let i = 0; i < this._systems.length; ++i) {
                this._systems[i].update(dt);
              }
              this._compScheduler.lateUpdatePhase(dt);
              this.emit("director_after_update");
              CCObject._deferredDestroy();
              for (let i = 0; i < this._systems.length; ++i) {
                this._systems[i].postUpdate(dt);
              }
            }
            this.emit("director_before_draw");
            uiRendererManager.updateAllDirtyRenderers();
            this._root.frameMove(dt);
            this.emit("director_after_draw");
            Node$1.resetHasChangedFlags();
            Node$1.clearNodeArray();
            scalableContainerManager.update(dt);
            this.emit("director_end_frame");
            this._totalFrames++;
          }
        }
        buildRenderPipeline() {
          if (!this._root) {
            return;
          }
          const ppl = this._root.customPipeline;
          const cameras = this._root.cameraList;
          ppl.beginSetup();
          const builder = cclegacy.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME);
          cclegacy.rendering.dispatchResizeEvents(cameras, builder, ppl);
          builder.setup(cameras, ppl);
          ppl.endSetup();
        }
        setupRenderPipelineBuilder() {
          if (macro.CUSTOM_PIPELINE_NAME !== '' && cclegacy.rendering && this._root && this._root.usesCustomPipeline) {
            this.on("director_before_render", this.buildRenderPipeline, this);
            this.on("director_before_scene_launch", cclegacy.rendering.forceResizeAllWindows, cclegacy.rendering);
          }
        }
        init() {
          this._totalFrames = 0;
          this._paused = false;
          this.registerSystem(Scheduler.ID, this._scheduler, 200);
          this._root = new Root(deviceManager.gfxDevice);
          const rootInfo = {};
          this._root.initialize(rootInfo);
          this.setupRenderPipelineBuilder();
          for (let i = 0; i < this._systems.length; i++) {
            this._systems[i].init();
          }
          this.emit("director_init");
        }
        addPersistRootNode(node) {
          if (!Node$1.isNode(node) || !node.uuid) {
            warnID(3800);
            return;
          }
          const id = node.uuid;
          if (!this._persistRootNodes[id]) {
            const 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);
          }
        }
        removePersistRootNode(node) {
          const id = node.uuid || '';
          if (node === this._persistRootNodes[id]) {
            delete this._persistRootNodes[id];
            node._persistNode = false;
            node._originalSceneId = '';
            releaseManager._removePersistNodeRef(node);
          }
        }
        isPersistRootNode(node) {
          return !!node._persistNode;
        }
      } exports("Director", Director);
      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;
      cclegacy.Director = Director;
      cclegacy.DirectorEvent = DirectorEvent;
      const director = exports("director", Director.instance = cclegacy.director = new Director());

      const ccwindow = typeof globalThis.jsb !== 'undefined' ? typeof jsb.window !== 'undefined' ? jsb.window : window : window;
      const ccdocument$4 = ccwindow.document;
      function findCanvas() {
        const container = ccdocument$4.createElement('div');
        const frame = ccdocument$4.documentElement;
        const canvas = ccwindow.__canvas;
        return {
          frame,
          canvas,
          container
        };
      }
      function loadJsFile(path) {
        if (window.oh && window.scriptEngineType === 'napi') {
          window.oh.loadModule(path);
          return Promise.resolve();
        } else {
          return require(`${path}`);
        }
      }

      class Pacer {
        constructor() {
          this._rafHandle = 0;
          this._onTick = null;
          this._targetFrameRate = 60;
          this._isPlaying = false;
          this._updateCallback = () => {
            if (this._isPlaying) {
              this._rafHandle = requestAnimationFrame(this._updateCallback);
            }
            if (this._onTick) {
              this._onTick();
            }
          };
        }
        get targetFrameRate() {
          return this._targetFrameRate;
        }
        set targetFrameRate(val) {
          if (this._targetFrameRate !== val) {
            assertIsTrue(val > 0);
            this._targetFrameRate = val;
            jsb.setPreferredFramesPerSecond(this._targetFrameRate);
            if (this._isPlaying) {
              this.stop();
              this.start();
            }
          }
        }
        set onTick(val) {
          this._onTick = val;
        }
        get onTick() {
          return this._onTick;
        }
        start() {
          if (this._isPlaying) return;
          this._rafHandle = requestAnimationFrame(this._updateCallback);
          this._isPlaying = true;
        }
        stop() {
          if (!this._isPlaying) return;
          cancelAnimationFrame(this._rafHandle);
          this._rafHandle = 0;
          this._isPlaying = false;
        }
      }

      var _class$2e, _class2$1T, _class3$B, _class4$p, _class5$n, _class6$8, _class7$5, _class8$4, _class10$3, _class11$3, _class12$2, _class13$2, _class14$2, _class15$1;
      const PIPELINE_FLOW_MAIN = 'MainFlow';
      const PIPELINE_FLOW_FORWARD = 'ForwardFlow';
      const PIPELINE_FLOW_SHADOW = 'ShadowFlow';
      const PIPELINE_FLOW_SMAA = 'SMAAFlow';
      const PIPELINE_FLOW_TONEMAP = 'ToneMapFlow';
      const RenderPassStage = {
        "DEFAULT": 100,
        "UI": 200
      };
      cclegacy.RenderPassStage = RenderPassStage;
      const RenderPriority = {
        "MIN": 0,
        "MAX": 255,
        "DEFAULT": 128
      };
      const globalDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      const localDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      const PipelineGlobalBindings = {
        "UBO_GLOBAL": 0,
        "UBO_CAMERA": 1,
        "UBO_SHADOW": 2,
        "UBO_CSM": 3,
        "SAMPLER_SHADOWMAP": 4,
        "SAMPLER_ENVIRONMENT": 5,
        "SAMPLER_SPOT_SHADOW_MAP": 6,
        "SAMPLER_DIFFUSEMAP": 7,
        "COUNT": 8
      };
      const GLOBAL_UBO_COUNT = 4;
      const GLOBAL_SAMPLER_COUNT = 8 - GLOBAL_UBO_COUNT;
      const ModelLocalBindings = {
        "UBO_LOCAL": 0,
        "UBO_FORWARD_LIGHTS": 1,
        "UBO_SKINNING_ANIMATION": 2,
        "UBO_SKINNING_TEXTURE": 3,
        "UBO_MORPH": 4,
        "UBO_UI_LOCAL": 5,
        "UBO_SH": 6,
        "SAMPLER_JOINTS": 7,
        "SAMPLER_MORPH_POSITION": 8,
        "SAMPLER_MORPH_NORMAL": 9,
        "SAMPLER_MORPH_TANGENT": 10,
        "SAMPLER_LIGHTMAP": 11,
        "SAMPLER_SPRITE": 12,
        "SAMPLER_REFLECTION": 13,
        "STORAGE_REFLECTION": 14,
        "SAMPLER_REFLECTION_PROBE_CUBE": 15,
        "SAMPLER_REFLECTION_PROBE_PLANAR": 16,
        "SAMPLER_REFLECTION_PROBE_DATA_MAP": 17,
        "SAMPLER_REFLECTION_PROBE_BLEND_CUBE": 18,
        "COUNT": 19
      };
      const LOCAL_UBO_COUNT = 7;
      const LOCAL_SAMPLER_COUNT = 14 - LOCAL_UBO_COUNT;
      const LOCAL_STORAGE_IMAGE_COUNT = 19 - LOCAL_UBO_COUNT - LOCAL_SAMPLER_COUNT;
      const SetIndex = {
        "GLOBAL": 0,
        "MATERIAL": 1,
        "LOCAL": 2,
        "COUNT": 3
      };
      const 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]);
      const UBOGlobalEnum = {
        "TIME_OFFSET": 0,
        "SCREEN_SIZE_OFFSET": 4,
        "NATIVE_SIZE_OFFSET": 8,
        "PROBE_INFO_OFFSET": 12,
        "DEBUG_VIEW_MODE_OFFSET": 16,
        "COUNT": 20,
        "SIZE": 80
      };
      class UBOGlobal {}
      _class$2e = UBOGlobal;
      UBOGlobal.TIME_OFFSET = 0;
      UBOGlobal.SCREEN_SIZE_OFFSET = 4;
      UBOGlobal.NATIVE_SIZE_OFFSET = 8;
      UBOGlobal.PROBE_INFO_OFFSET = 12;
      UBOGlobal.DEBUG_VIEW_MODE_OFFSET = 16;
      UBOGlobal.COUNT = 20;
      UBOGlobal.SIZE = 80;
      UBOGlobal.NAME = 'CCGlobal';
      UBOGlobal.BINDING = 0;
      UBOGlobal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class$2e.BINDING, 1, 1, 63);
      UBOGlobal.LAYOUT = new UniformBlock(0, _class$2e.BINDING, _class$2e.NAME, [new Uniform('cc_time', 16, 1), new Uniform('cc_screenSize', 16, 1), new Uniform('cc_nativeSize', 16, 1), new Uniform('cc_probeInfo', 16, 1), new Uniform('cc_debug_view_mode', 16, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOGlobal.BINDING] = UBOGlobal.DESCRIPTOR;
      const UBOCameraEnum = {
        "MAT_VIEW_OFFSET": 0,
        "MAT_VIEW_INV_OFFSET": 16,
        "MAT_PROJ_OFFSET": 32,
        "MAT_PROJ_INV_OFFSET": 48,
        "MAT_VIEW_PROJ_OFFSET": 64,
        "MAT_VIEW_PROJ_INV_OFFSET": 80,
        "CAMERA_POS_OFFSET": 96,
        "SURFACE_TRANSFORM_OFFSET": 100,
        "SCREEN_SCALE_OFFSET": 104,
        "EXPOSURE_OFFSET": 108,
        "MAIN_LIT_DIR_OFFSET": 112,
        "MAIN_LIT_COLOR_OFFSET": 116,
        "AMBIENT_SKY_OFFSET": 120,
        "AMBIENT_GROUND_OFFSET": 124,
        "GLOBAL_FOG_COLOR_OFFSET": 128,
        "GLOBAL_FOG_BASE_OFFSET": 132,
        "GLOBAL_FOG_ADD_OFFSET": 136,
        "NEAR_FAR_OFFSET": 140,
        "VIEW_PORT_OFFSET": 144,
        "COUNT": 148,
        "SIZE": 592
      };
      class UBOCamera {}
      _class2$1T = UBOCamera;
      UBOCamera.MAT_VIEW_OFFSET = 0;
      UBOCamera.MAT_VIEW_INV_OFFSET = 16;
      UBOCamera.MAT_PROJ_OFFSET = 32;
      UBOCamera.MAT_PROJ_INV_OFFSET = 48;
      UBOCamera.MAT_VIEW_PROJ_OFFSET = 64;
      UBOCamera.MAT_VIEW_PROJ_INV_OFFSET = 80;
      UBOCamera.CAMERA_POS_OFFSET = 96;
      UBOCamera.SURFACE_TRANSFORM_OFFSET = 100;
      UBOCamera.SCREEN_SCALE_OFFSET = 104;
      UBOCamera.EXPOSURE_OFFSET = 108;
      UBOCamera.MAIN_LIT_DIR_OFFSET = 112;
      UBOCamera.MAIN_LIT_COLOR_OFFSET = 116;
      UBOCamera.AMBIENT_SKY_OFFSET = 120;
      UBOCamera.AMBIENT_GROUND_OFFSET = 124;
      UBOCamera.GLOBAL_FOG_COLOR_OFFSET = 128;
      UBOCamera.GLOBAL_FOG_BASE_OFFSET = 132;
      UBOCamera.GLOBAL_FOG_ADD_OFFSET = 136;
      UBOCamera.NEAR_FAR_OFFSET = 140;
      UBOCamera.VIEW_PORT_OFFSET = 144;
      UBOCamera.COUNT = 148;
      UBOCamera.SIZE = 592;
      UBOCamera.NAME = 'CCCamera';
      UBOCamera.BINDING = 1;
      UBOCamera.DESCRIPTOR = new DescriptorSetLayoutBinding(_class2$1T.BINDING, 1, 1, 63);
      UBOCamera.LAYOUT = new UniformBlock(0, _class2$1T.BINDING, _class2$1T.NAME, [new Uniform('cc_matView', 25, 1), new Uniform('cc_matViewInv', 25, 1), new Uniform('cc_matProj', 25, 1), new Uniform('cc_matProjInv', 25, 1), new Uniform('cc_matViewProj', 25, 1), new Uniform('cc_matViewProjInv', 25, 1), new Uniform('cc_cameraPos', 16, 1), new Uniform('cc_surfaceTransform', 16, 1), new Uniform('cc_screenScale', 16, 1), new Uniform('cc_exposure', 16, 1), new Uniform('cc_mainLitDir', 16, 1), new Uniform('cc_mainLitColor', 16, 1), new Uniform('cc_ambientSky', 16, 1), new Uniform('cc_ambientGround', 16, 1), new Uniform('cc_fogColor', 16, 1), new Uniform('cc_fogBase', 16, 1), new Uniform('cc_fogAdd', 16, 1), new Uniform('cc_nearFar', 16, 1), new Uniform('cc_viewPort', 16, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR;
      const UBOShadowEnum = {
        "MAT_LIGHT_VIEW_OFFSET": 0,
        "MAT_LIGHT_VIEW_PROJ_OFFSET": 16,
        "SHADOW_INV_PROJ_DEPTH_INFO_OFFSET": 32,
        "SHADOW_PROJ_DEPTH_INFO_OFFSET": 36,
        "SHADOW_PROJ_INFO_OFFSET": 40,
        "SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET": 44,
        "SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET": 48,
        "SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET": 52,
        "SHADOW_COLOR_OFFSET": 56,
        "PLANAR_NORMAL_DISTANCE_INFO_OFFSET": 60,
        "COUNT": 64,
        "SIZE": 256
      };
      class UBOShadow {}
      _class3$B = UBOShadow;
      UBOShadow.MAT_LIGHT_VIEW_OFFSET = 0;
      UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET = 16;
      UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = 32;
      UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET = 36;
      UBOShadow.SHADOW_PROJ_INFO_OFFSET = 40;
      UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = 44;
      UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = 48;
      UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = 52;
      UBOShadow.SHADOW_COLOR_OFFSET = 56;
      UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET = 60;
      UBOShadow.COUNT = 64;
      UBOShadow.SIZE = 256;
      UBOShadow.NAME = 'CCShadow';
      UBOShadow.BINDING = 2;
      UBOShadow.DESCRIPTOR = new DescriptorSetLayoutBinding(_class3$B.BINDING, 1, 1, 63);
      UBOShadow.LAYOUT = new UniformBlock(0, _class3$B.BINDING, _class3$B.NAME, [new Uniform('cc_matLightView', 25, 1), new Uniform('cc_matLightViewProj', 25, 1), new Uniform('cc_shadowInvProjDepthInfo', 16, 1), new Uniform('cc_shadowProjDepthInfo', 16, 1), new Uniform('cc_shadowProjInfo', 16, 1), new Uniform('cc_shadowNFLSInfo', 16, 1), new Uniform('cc_shadowWHPBInfo', 16, 1), new Uniform('cc_shadowLPNNInfo', 16, 1), new Uniform('cc_shadowColor', 16, 1), new Uniform('cc_planarNDInfo', 16, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR;
      const UBOCSMEnum = {
        "CSM_LEVEL_COUNT": 4,
        "CSM_VIEW_DIR_0_OFFSET": 0,
        "CSM_VIEW_DIR_1_OFFSET": 16,
        "CSM_VIEW_DIR_2_OFFSET": 32,
        "CSM_ATLAS_OFFSET": 48,
        "MAT_CSM_VIEW_PROJ_OFFSET": 64,
        "CSM_PROJ_DEPTH_INFO_OFFSET": 128,
        "CSM_PROJ_INFO_OFFSET": 144,
        "CSM_SPLITS_INFO_OFFSET": 160,
        "COUNT": 164,
        "SIZE": 656
      };
      class UBOCSM {}
      _class4$p = UBOCSM;
      UBOCSM.CSM_LEVEL_COUNT = 4;
      UBOCSM.CSM_VIEW_DIR_0_OFFSET = 0;
      UBOCSM.CSM_VIEW_DIR_1_OFFSET = 16;
      UBOCSM.CSM_VIEW_DIR_2_OFFSET = 32;
      UBOCSM.CSM_ATLAS_OFFSET = 48;
      UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET = 64;
      UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET = 128;
      UBOCSM.CSM_PROJ_INFO_OFFSET = 144;
      UBOCSM.CSM_SPLITS_INFO_OFFSET = 160;
      UBOCSM.COUNT = 164;
      UBOCSM.SIZE = 656;
      UBOCSM.NAME = 'CCCSM';
      UBOCSM.BINDING = 3;
      UBOCSM.DESCRIPTOR = new DescriptorSetLayoutBinding(_class4$p.BINDING, 1, 1, 16);
      UBOCSM.LAYOUT = new UniformBlock(0, _class4$p.BINDING, _class4$p.NAME, [new Uniform('cc_csmViewDir0', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir1', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir2', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmAtlas', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_matCSMViewProj', 25, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmProjDepthInfo', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmProjInfo', 16, _class4$p.CSM_LEVEL_COUNT), new Uniform('cc_csmSplitsInfo', 16, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCSM.BINDING] = UBOCSM.DESCRIPTOR;
      const UNIFORM_SHADOWMAP_NAME = 'cc_shadowMap';
      const UNIFORM_SHADOWMAP_BINDING = 4;
      const UNIFORM_SHADOWMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SHADOWMAP_BINDING, 16, 1, 16);
      const UNIFORM_SHADOWMAP_LAYOUT = new UniformSamplerTexture(0, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SHADOWMAP_NAME, 28, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_SHADOWMAP_NAME] = UNIFORM_SHADOWMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_SHADOWMAP_BINDING] = UNIFORM_SHADOWMAP_DESCRIPTOR;
      const UNIFORM_ENVIRONMENT_NAME = 'cc_environment';
      const UNIFORM_ENVIRONMENT_BINDING = 5;
      const UNIFORM_ENVIRONMENT_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_ENVIRONMENT_BINDING, 16, 1, 16);
      const UNIFORM_ENVIRONMENT_LAYOUT = new UniformSamplerTexture(0, UNIFORM_ENVIRONMENT_BINDING, UNIFORM_ENVIRONMENT_NAME, 31, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_ENVIRONMENT_NAME] = UNIFORM_ENVIRONMENT_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_ENVIRONMENT_BINDING] = UNIFORM_ENVIRONMENT_DESCRIPTOR;
      const UNIFORM_DIFFUSEMAP_NAME = 'cc_diffuseMap';
      const UNIFORM_DIFFUSEMAP_BINDING = 7;
      const UNIFORM_DIFFUSEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_DIFFUSEMAP_BINDING, 16, 1, 16);
      const UNIFORM_DIFFUSEMAP_LAYOUT = new UniformSamplerTexture(0, UNIFORM_DIFFUSEMAP_BINDING, UNIFORM_DIFFUSEMAP_NAME, 31, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_DIFFUSEMAP_NAME] = UNIFORM_DIFFUSEMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_DIFFUSEMAP_BINDING] = UNIFORM_DIFFUSEMAP_DESCRIPTOR;
      const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME = 'cc_spotShadowMap';
      const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING = 6;
      const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, 16, 1, 16);
      const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(0, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME, 28, 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;
      const UBOLocalEnum = {
        "MAT_WORLD_OFFSET": 0,
        "MAT_WORLD_IT_OFFSET": 16,
        "LIGHTINGMAP_UVPARAM": 32,
        "LOCAL_SHADOW_BIAS": 36,
        "REFLECTION_PROBE_DATA1": 40,
        "REFLECTION_PROBE_DATA2": 44,
        "REFLECTION_PROBE_BLEND_DATA1": 48,
        "REFLECTION_PROBE_BLEND_DATA2": 52,
        "COUNT": 56,
        "SIZE": 224
      };
      class UBOLocal {}
      _class5$n = UBOLocal;
      UBOLocal.MAT_WORLD_OFFSET = 0;
      UBOLocal.MAT_WORLD_IT_OFFSET = 16;
      UBOLocal.LIGHTINGMAP_UVPARAM = 32;
      UBOLocal.LOCAL_SHADOW_BIAS = 36;
      UBOLocal.REFLECTION_PROBE_DATA1 = 40;
      UBOLocal.REFLECTION_PROBE_DATA2 = 44;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA1 = 48;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA2 = 52;
      UBOLocal.COUNT = 56;
      UBOLocal.SIZE = 224;
      UBOLocal.NAME = 'CCLocal';
      UBOLocal.BINDING = 0;
      UBOLocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class5$n.BINDING, 1, 1, 1 | 16 | 32);
      UBOLocal.LAYOUT = new UniformBlock(2, _class5$n.BINDING, _class5$n.NAME, [new Uniform('cc_matWorld', 25, 1), new Uniform('cc_matWorldIT', 25, 1), new Uniform('cc_lightingMapUVParam', 16, 1), new Uniform('cc_localShadowBias', 16, 1), new Uniform('cc_reflectionProbeData1', 16, 1), new Uniform('cc_reflectionProbeData2', 16, 1), new Uniform('cc_reflectionProbeBlendData1', 16, 1), new Uniform('cc_reflectionProbeBlendData2', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOLocal.NAME] = UBOLocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocal.BINDING] = UBOLocal.DESCRIPTOR;
      class 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 = 0;
      UBOWorldBound.DESCRIPTOR = new DescriptorSetLayoutBinding(_class6$8.BINDING, 1, 1, 1 | 32);
      UBOWorldBound.LAYOUT = new UniformBlock(2, _class6$8.BINDING, _class6$8.NAME, [new Uniform('cc_worldBoundCenter', 16, 1), new Uniform('cc_worldBoundHalfExtents', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOWorldBound.NAME] = UBOWorldBound.LAYOUT;
      localDescriptorSetLayout.bindings[UBOWorldBound.BINDING] = UBOWorldBound.DESCRIPTOR;
      const INST_MAT_WORLD = 'a_matWorld0';
      const INST_SH = 'a_sh_linear_const_r';
      class UBOLocalBatched {}
      _class7$5 = UBOLocalBatched;
      UBOLocalBatched.BATCHING_COUNT = 10;
      UBOLocalBatched.MAT_WORLDS_OFFSET = 0;
      UBOLocalBatched.COUNT = 16 * _class7$5.BATCHING_COUNT;
      UBOLocalBatched.SIZE = _class7$5.COUNT * 4;
      UBOLocalBatched.NAME = 'CCLocalBatched';
      UBOLocalBatched.BINDING = 0;
      UBOLocalBatched.DESCRIPTOR = new DescriptorSetLayoutBinding(_class7$5.BINDING, 1, 1, 1 | 32);
      UBOLocalBatched.LAYOUT = new UniformBlock(2, _class7$5.BINDING, _class7$5.NAME, [new Uniform('cc_matWorlds', 25, _class7$5.BATCHING_COUNT)], 1);
      localDescriptorSetLayout.layouts[UBOLocalBatched.NAME] = UBOLocalBatched.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocalBatched.BINDING] = UBOLocalBatched.DESCRIPTOR;
      const UBOForwardLightEnum = {
        "LIGHTS_PER_PASS": 1,
        "LIGHT_POS_OFFSET": 0,
        "LIGHT_COLOR_OFFSET": 4,
        "LIGHT_SIZE_RANGE_ANGLE_OFFSET": 8,
        "LIGHT_DIR_OFFSET": 12,
        "LIGHT_BOUNDING_SIZE_VS_OFFSET": 16,
        "COUNT": 20,
        "SIZE": 80
      };
      class UBOForwardLight {}
      _class8$4 = UBOForwardLight;
      UBOForwardLight.LIGHTS_PER_PASS = 1;
      UBOForwardLight.LIGHT_POS_OFFSET = 0;
      UBOForwardLight.LIGHT_COLOR_OFFSET = 4;
      UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET = 8;
      UBOForwardLight.LIGHT_DIR_OFFSET = 12;
      UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET = 16;
      UBOForwardLight.COUNT = 20;
      UBOForwardLight.SIZE = 80;
      UBOForwardLight.NAME = 'CCForwardLight';
      UBOForwardLight.BINDING = 1;
      UBOForwardLight.DESCRIPTOR = new DescriptorSetLayoutBinding(_class8$4.BINDING, 2, 1, 16);
      UBOForwardLight.LAYOUT = new UniformBlock(2, _class8$4.BINDING, _class8$4.NAME, [new Uniform('cc_lightPos', 16, 1), new Uniform('cc_lightColor', 16, 1), new Uniform('cc_lightSizeRangeAngle', 16, 1), new Uniform('cc_lightDir', 16, 1), new Uniform('cc_lightBoundingSizeVS', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOForwardLight.NAME] = UBOForwardLight.LAYOUT;
      localDescriptorSetLayout.bindings[UBOForwardLight.BINDING] = UBOForwardLight.DESCRIPTOR;
      class UBODeferredLight {}
      UBODeferredLight.LIGHTS_PER_PASS = 10;
      const JOINT_UNIFORM_CAPACITY = 30;
      class UBOSkinningTexture {}
      _class10$3 = UBOSkinningTexture;
      UBOSkinningTexture.JOINTS_TEXTURE_INFO_OFFSET = 0;
      UBOSkinningTexture.COUNT = _class10$3.JOINTS_TEXTURE_INFO_OFFSET + 4;
      UBOSkinningTexture.SIZE = _class10$3.COUNT * 4;
      UBOSkinningTexture.NAME = 'CCSkinningTexture';
      UBOSkinningTexture.BINDING = 3;
      UBOSkinningTexture.DESCRIPTOR = new DescriptorSetLayoutBinding(_class10$3.BINDING, 1, 1, 1);
      UBOSkinningTexture.LAYOUT = new UniformBlock(2, _class10$3.BINDING, _class10$3.NAME, [new Uniform('cc_jointTextureInfo', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningTexture.NAME] = UBOSkinningTexture.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningTexture.BINDING] = UBOSkinningTexture.DESCRIPTOR;
      class UBOSkinningAnimation {}
      _class11$3 = UBOSkinningAnimation;
      UBOSkinningAnimation.JOINTS_ANIM_INFO_OFFSET = 0;
      UBOSkinningAnimation.COUNT = _class11$3.JOINTS_ANIM_INFO_OFFSET + 4;
      UBOSkinningAnimation.SIZE = _class11$3.COUNT * 4;
      UBOSkinningAnimation.NAME = 'CCSkinningAnimation';
      UBOSkinningAnimation.BINDING = 2;
      UBOSkinningAnimation.DESCRIPTOR = new DescriptorSetLayoutBinding(_class11$3.BINDING, 1, 1, 1);
      UBOSkinningAnimation.LAYOUT = new UniformBlock(2, _class11$3.BINDING, _class11$3.NAME, [new Uniform('cc_jointAnimInfo', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningAnimation.NAME] = UBOSkinningAnimation.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAnimation.DESCRIPTOR;
      const INST_JOINT_ANIM_INFO = 'a_jointAnimInfo';
      class UBOSkinning {
        static get JOINT_UNIFORM_CAPACITY() {
          return UBOSkinning._jointUniformCapacity;
        }
        static get COUNT() {
          return UBOSkinning._count;
        }
        static get SIZE() {
          return UBOSkinning._size;
        }
        static initLayout(capacity) {
          UBOSkinning._jointUniformCapacity = capacity;
          UBOSkinning._count = capacity * 12;
          UBOSkinning._size = UBOSkinning._count * 4;
          UBOSkinning.LAYOUT.members[0].count = capacity * 3;
        }
      }
      _class12$2 = UBOSkinning;
      UBOSkinning._jointUniformCapacity = 0;
      UBOSkinning._count = 0;
      UBOSkinning._size = 0;
      UBOSkinning.NAME = 'CCSkinning';
      UBOSkinning.BINDING = 3;
      UBOSkinning.DESCRIPTOR = new DescriptorSetLayoutBinding(_class12$2.BINDING, 1, 1, 1);
      UBOSkinning.LAYOUT = new UniformBlock(2, _class12$2.BINDING, _class12$2.NAME, [new Uniform('cc_joints', 16, 1)], 1);
      function localDescriptorSetLayout_ResizeMaxJoints(maxCount) {
        UBOSkinning.initLayout(maxCount);
        localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT;
        localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR;
      }
      const UBOMorphEnum = {
        "MAX_MORPH_TARGET_COUNT": 60,
        "OFFSET_OF_WEIGHTS": 0,
        "OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH": 240,
        "OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT": 244,
        "OFFSET_OF_VERTICES_COUNT": 248,
        "COUNT_BASE_4_BYTES": 64,
        "SIZE": 256
      };
      class UBOMorph {}
      _class13$2 = UBOMorph;
      UBOMorph.MAX_MORPH_TARGET_COUNT = 60;
      UBOMorph.OFFSET_OF_WEIGHTS = 0;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 240;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = 244;
      UBOMorph.OFFSET_OF_VERTICES_COUNT = 248;
      UBOMorph.COUNT_BASE_4_BYTES = 64;
      UBOMorph.SIZE = 256;
      UBOMorph.NAME = 'CCMorph';
      UBOMorph.BINDING = 4;
      UBOMorph.DESCRIPTOR = new DescriptorSetLayoutBinding(_class13$2.BINDING, 1, 1, 1);
      UBOMorph.LAYOUT = new UniformBlock(2, _class13$2.BINDING, _class13$2.NAME, [new Uniform('cc_displacementWeights', 16, 60 / 4), new Uniform('cc_displacementTextureInfo', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOMorph.NAME] = UBOMorph.LAYOUT;
      localDescriptorSetLayout.bindings[UBOMorph.BINDING] = UBOMorph.DESCRIPTOR;
      class UBOUILocal {}
      _class14$2 = UBOUILocal;
      UBOUILocal.NAME = 'CCUILocal';
      UBOUILocal.BINDING = 5;
      UBOUILocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class14$2.BINDING, 2, 1, 1);
      UBOUILocal.LAYOUT = new UniformBlock(2, _class14$2.BINDING, _class14$2.NAME, [new Uniform('cc_local_data', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOUILocal.NAME] = UBOUILocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOUILocal.BINDING] = UBOUILocal.DESCRIPTOR;
      const UBOSHEnum = {
        "SH_LINEAR_CONST_R_OFFSET": 0,
        "SH_LINEAR_CONST_G_OFFSET": 4,
        "SH_LINEAR_CONST_B_OFFSET": 8,
        "SH_QUADRATIC_R_OFFSET": 12,
        "SH_QUADRATIC_G_OFFSET": 16,
        "SH_QUADRATIC_B_OFFSET": 20,
        "SH_QUADRATIC_A_OFFSET": 24,
        "COUNT": 28,
        "SIZE": 112
      };
      class UBOSH {}
      _class15$1 = UBOSH;
      UBOSH.SH_LINEAR_CONST_R_OFFSET = 0;
      UBOSH.SH_LINEAR_CONST_G_OFFSET = 4;
      UBOSH.SH_LINEAR_CONST_B_OFFSET = 8;
      UBOSH.SH_QUADRATIC_R_OFFSET = 12;
      UBOSH.SH_QUADRATIC_G_OFFSET = 16;
      UBOSH.SH_QUADRATIC_B_OFFSET = 20;
      UBOSH.SH_QUADRATIC_A_OFFSET = 24;
      UBOSH.COUNT = 28;
      UBOSH.SIZE = 112;
      UBOSH.NAME = 'CCSH';
      UBOSH.BINDING = 6;
      UBOSH.DESCRIPTOR = new DescriptorSetLayoutBinding(_class15$1.BINDING, 1, 1, 16);
      UBOSH.LAYOUT = new UniformBlock(2, _class15$1.BINDING, _class15$1.NAME, [new Uniform('cc_sh_linear_const_r', 16, 1), new Uniform('cc_sh_linear_const_g', 16, 1), new Uniform('cc_sh_linear_const_b', 16, 1), new Uniform('cc_sh_quadratic_r', 16, 1), new Uniform('cc_sh_quadratic_g', 16, 1), new Uniform('cc_sh_quadratic_b', 16, 1), new Uniform('cc_sh_quadratic_a', 16, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSH.NAME] = UBOSH.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSH.BINDING] = UBOSH.DESCRIPTOR;
      const UNIFORM_JOINT_TEXTURE_NAME = 'cc_jointTexture';
      const UNIFORM_JOINT_TEXTURE_BINDING = 7;
      const UNIFORM_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_JOINT_TEXTURE_BINDING, 16, 1, 1);
      const UNIFORM_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_JOINT_TEXTURE_BINDING, UNIFORM_JOINT_TEXTURE_NAME, 28, 1);
      localDescriptorSetLayout.layouts[UNIFORM_JOINT_TEXTURE_NAME] = UNIFORM_JOINT_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_JOINT_TEXTURE_BINDING] = UNIFORM_JOINT_TEXTURE_DESCRIPTOR;
      const UNIFORM_REALTIME_JOINT_TEXTURE_NAME = 'cc_realtimeJoint';
      const UNIFORM_REALTIME_JOINT_TEXTURE_BINDING = 7;
      const UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, 16, 1, 1);
      const UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, UNIFORM_REALTIME_JOINT_TEXTURE_NAME, 28, 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;
      const UNIFORM_POSITION_MORPH_TEXTURE_NAME = 'cc_PositionDisplacements';
      const UNIFORM_POSITION_MORPH_TEXTURE_BINDING = 8;
      const UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_POSITION_MORPH_TEXTURE_BINDING, 16, 1, 1);
      const UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_NAME, 28, 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;
      const UNIFORM_NORMAL_MORPH_TEXTURE_NAME = 'cc_NormalDisplacements';
      const UNIFORM_NORMAL_MORPH_TEXTURE_BINDING = 9;
      const UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, 16, 1, 1);
      const UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_NORMAL_MORPH_TEXTURE_NAME, 28, 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;
      const UNIFORM_TANGENT_MORPH_TEXTURE_NAME = 'cc_TangentDisplacements';
      const UNIFORM_TANGENT_MORPH_TEXTURE_BINDING = 10;
      const UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, 16, 1, 1);
      const UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_NAME, 28, 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;
      const UNIFORM_LIGHTMAP_TEXTURE_NAME = 'cc_lightingMap';
      const UNIFORM_LIGHTMAP_TEXTURE_BINDING = 11;
      const UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTMAP_TEXTURE_BINDING, 16, 1, 16);
      const UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_LIGHTMAP_TEXTURE_NAME, 28, 1);
      localDescriptorSetLayout.layouts[UNIFORM_LIGHTMAP_TEXTURE_NAME] = UNIFORM_LIGHTMAP_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_LIGHTMAP_TEXTURE_BINDING] = UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR;
      const UNIFORM_SPRITE_TEXTURE_NAME = 'cc_spriteTexture';
      const UNIFORM_SPRITE_TEXTURE_BINDING = 12;
      const UNIFORM_SPRITE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPRITE_TEXTURE_BINDING, 16, 1, 16);
      const UNIFORM_SPRITE_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_SPRITE_TEXTURE_BINDING, UNIFORM_SPRITE_TEXTURE_NAME, 28, 1);
      localDescriptorSetLayout.layouts[UNIFORM_SPRITE_TEXTURE_NAME] = UNIFORM_SPRITE_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_SPRITE_TEXTURE_BINDING] = UNIFORM_SPRITE_TEXTURE_DESCRIPTOR;
      const UNIFORM_REFLECTION_TEXTURE_NAME = 'cc_reflectionTexture';
      const UNIFORM_REFLECTION_TEXTURE_BINDING = 13;
      const UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_TEXTURE_BINDING, 16, 1, 16);
      const UNIFORM_REFLECTION_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_TEXTURE_NAME, 28, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_TEXTURE_NAME] = UNIFORM_REFLECTION_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_TEXTURE_BINDING] = UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR;
      const UNIFORM_REFLECTION_STORAGE_NAME = 'cc_reflectionStorage';
      const UNIFORM_REFLECTION_STORAGE_BINDING = 14;
      const UNIFORM_REFLECTION_STORAGE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_STORAGE_BINDING, 128, 1, 32);
      const UNIFORM_REFLECTION_STORAGE_LAYOUT = new UniformStorageImage(2, UNIFORM_REFLECTION_STORAGE_BINDING, UNIFORM_REFLECTION_STORAGE_NAME, 41, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_STORAGE_NAME] = UNIFORM_REFLECTION_STORAGE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_STORAGE_BINDING] = UNIFORM_REFLECTION_STORAGE_DESCRIPTOR;
      const UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME = 'cc_reflectionProbeCubemap';
      const UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING = 15;
      const UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, 16, 1, 16);
      const UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME, 31, 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;
      const UNIFORM_REFLECTION_PROBE_TEXTURE_NAME = 'cc_reflectionProbePlanarMap';
      const UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING = 16;
      const UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, 16, 1, 16);
      const UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_NAME, 28, 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;
      const UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME = 'cc_reflectionProbeDataMap';
      const UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING = 17;
      const UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, 16, 1, 16);
      const UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME, 28, 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;
      const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME = 'cc_reflectionProbeBlendCubemap';
      const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING = 18;
      const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, 16, 1, 16);
      const UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT = new UniformSamplerTexture(2, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME, 31, 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;
      const CAMERA_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER]);
      const CAMERA_EDITOR_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.PROFILER]);
      const MODEL_ALWAYS_MASK = Layers.Enum.ALL;
      function supportsR16HalfFloatTexture(device) {
        return (device.getFormatFeatures(8) & (1 | 2)) === (1 | 2);
      }
      let dftShadowTexture;
      function getDefaultShadowTexture(device) {
        if (dftShadowTexture) return dftShadowTexture;
        const texInfo = new TextureInfo(1, 0, supportsR32FloatTexture(device) ? 11 : 35, 16, 16, 0, 1, 1, 1, 1);
        dftShadowTexture = device.createTexture(texInfo);
        return dftShadowTexture;
      }
      function supportsR32FloatTexture(device) {
        return (device.getFormatFeatures(11) & (1 | 2)) === (1 | 2) && !(device.gfxAPI === 6);
      }
      function supportsRGBA16HalfFloatTexture(device) {
        return (device.getFormatFeatures(41) & (1 | 2)) === (1 | 2);
      }
      function supportsRGBA32FloatTexture(device) {
        return (device.getFormatFeatures(44) & (1 | 2)) === (1 | 2);
      }
      function isEnableEffect() {
        return !!(cclegacy.rendering && cclegacy.rendering.enableEffectImport);
      }

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

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

      class PipelineInputAssemblerData {
        constructor() {
          this.quadIB = null;
          this.quadVB = null;
          this.quadIA = null;
        }
      } exports("PipelineInputAssemblerData", PipelineInputAssemblerData);

      const InstancedBuffer = exports("InstancedBuffer", nr.InstancedBuffer);
      const PipelineStateManager = exports("PipelineStateManager", nr.PipelineStateManager);
      let getOrCreatePipelineState = nr.PipelineStateManager.getOrCreatePipelineState;
      nr.PipelineStateManager.getOrCreatePipelineState = function (device, pass, shader, renderPass, ia) {
        return getOrCreatePipelineState(pass, shader, renderPass, ia);
      };

      const localWinSize = size();
      const orientationMap = {
        [macro.ORIENTATION_AUTO]: Orientation$1.AUTO,
        [macro.ORIENTATION_LANDSCAPE]: Orientation$1.LANDSCAPE,
        [macro.ORIENTATION_PORTRAIT]: Orientation$1.PORTRAIT
      };
      class View extends Eventify(System) {
        constructor() {
          super();
          this._designResolutionSize = size(0, 0);
          this._scaleX = 1;
          this._scaleY = 1;
          this._viewportRect = rect();
          this._visibleRect = rect();
          this._autoFullScreen = false;
          this._retinaEnabled = false;
          this._resizeCallback = null;
          const _strategyer = ContainerStrategy;
          const _strategy = ContentStrategy;
          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;
        }
        init() {
          const windowSize = screen.windowSize;
          const w = windowSize.width;
          const 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);
            const designResolution = settings.querySettings("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('fullscreen-change', this._updateAdaptResult, this);
        }
        resizeWithBrowserSize(enabled) {
          screenAdapter.handleResizeEvent = enabled;
        }
        setResizeCallback(callback) {
          if (typeof callback === 'function' || callback == null) {
            this._resizeCallback = callback;
          }
        }
        setOrientation(orientation) {
          screenAdapter.orientation = orientationMap[orientation];
        }
        adjustViewportMeta(enabled) {}
        enableRetina(enabled) {
          this._retinaEnabled = !!enabled;
        }
        isRetinaEnabled() {
          return this._retinaEnabled;
        }
        enableAutoFullScreen(enabled) {
          if (enabled === this._autoFullScreen) {
            return;
          }
          this._autoFullScreen = enabled;
          if (enabled) {
            screen.requestFullScreen().catch(e => {});
          }
        }
        isAutoFullScreenEnabled() {
          return this._autoFullScreen;
        }
        setCanvasSize(width, height) {
          screenAdapter.resolutionScale = 1;
          const dpr = screenAdapter.devicePixelRatio;
          const windowSize = new Size$1(width * dpr, height * dpr);
          screen.windowSize = windowSize;
        }
        getCanvasSize() {
          return screen.windowSize;
        }
        getFrameSize() {
          const dpr = screenAdapter.devicePixelRatio;
          const sizeInCssPixels = screen.windowSize;
          sizeInCssPixels.width /= dpr;
          sizeInCssPixels.height /= dpr;
          return sizeInCssPixels;
        }
        setFrameSize(width, height) {
          const dpr = screenAdapter.devicePixelRatio;
          screen.windowSize = new Size$1(width * dpr, height * dpr);
        }
        getVisibleSize() {
          return new Size$1(this._visibleRect.width, this._visibleRect.height);
        }
        getVisibleSizeInPixel() {
          return new Size$1(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY);
        }
        getVisibleOrigin() {
          return new Vec2(this._visibleRect.x, this._visibleRect.y);
        }
        getVisibleOriginInPixel() {
          return new Vec2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY);
        }
        getResolutionPolicy() {
          return this._resolutionPolicy;
        }
        _updateResolutionPolicy(resolutionPolicy) {
          if (resolutionPolicy instanceof ResolutionPolicy) {
            this._resolutionPolicy = resolutionPolicy;
          } else {
            const _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;
            }
          }
        }
        setResolutionPolicy(resolutionPolicy) {
          this._updateResolutionPolicy(resolutionPolicy);
          const designedResolution = view.getDesignResolutionSize();
          view.setDesignResolutionSize(designedResolution.width, designedResolution.height, resolutionPolicy);
        }
        setDesignResolutionSize(width, height, resolutionPolicy) {
          if (!(width > 0 && height > 0)) {
            errorID(2200);
            return;
          }
          this._updateResolutionPolicy(resolutionPolicy);
          const policy = this._resolutionPolicy;
          if (policy) {
            policy.preApply(this);
          }
          this._designResolutionSize.width = width;
          this._designResolutionSize.height = height;
          const 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) {
            const vp = this._viewportRect;
            const vb = this._visibleRect;
            const 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');
        }
        getDesignResolutionSize() {
          return new Size$1(this._designResolutionSize.width, this._designResolutionSize.height);
        }
        setRealPixelResolution(width, height, resolutionPolicy) {
          this.setDesignResolutionSize(width, height, resolutionPolicy);
        }
        getViewportRect() {
          return this._viewportRect;
        }
        getScaleX() {
          return this._scaleX;
        }
        getScaleY() {
          return this._scaleY;
        }
        getDevicePixelRatio() {
          return screenAdapter.devicePixelRatio;
        }
        convertToLocationInView(tx, ty, relatedPos, out = new Vec2()) {
          const x = screenAdapter.devicePixelRatio * (tx - relatedPos.left);
          const 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;
        }
        _convertToUISpace(point) {
          const viewport = this._viewportRect;
          point.x = (point.x - viewport.x) / this._scaleX;
          point.y = (point.y - viewport.y) / this._scaleY;
        }
        _updateAdaptResult(width, height, windowId) {
          var _this$_resizeCallback;
          cclegacy.director.root.resize(width, height, windowId === undefined || windowId === 0 ? 1 : windowId);
          const w = this._designResolutionSize.width;
          const h = this._designResolutionSize.height;
          if (width > 0 && height > 0) {
            this.setDesignResolutionSize(w, h, this._resolutionPolicy);
          } else {
            assert(false, '_updateAdaptResult Invalid size.');
          }
          this.emit('canvas-resize');
          (_this$_resizeCallback = this._resizeCallback) === null || _this$_resizeCallback === void 0 ? void 0 : _this$_resizeCallback.call(this);
        }
      } exports("View", View);
      View.instance = void 0;
      class ContainerStrategy {
        constructor() {
          this.name = 'ContainerStrategy';
        }
        preApply(_view) {}
        apply(_view, designedResolution) {}
        postApply(_view) {}
        _setupCanvas() {
          const locCanvas = cclegacy.game.canvas;
          if (locCanvas) {
            const windowSize = screen.windowSize;
            if (locCanvas.width !== windowSize.width) {
              locCanvas.width = windowSize.width;
            }
            if (locCanvas.height !== windowSize.height) {
              locCanvas.height = windowSize.height;
            }
          }
        }
      }
      ContainerStrategy.EQUAL_TO_FRAME = void 0;
      ContainerStrategy.PROPORTION_TO_FRAME = void 0;
      class ContentStrategy {
        get strategy() {
          return this._strategy;
        }
        constructor() {
          this.name = 'ContentStrategy';
          this._result = {
            scale: [1, 1],
            viewport: null
          };
          this._strategy = ResolutionPolicy.UNKNOWN;
        }
        preApply(_view) {}
        apply(_view, designedResolution) {
          return {
            scale: [1, 1]
          };
        }
        postApply(_view) {}
        _buildResult(containerW, containerH, contentW, contentH, scaleX, scaleY) {
          if (Math.abs(containerW - contentW) < 2) {
            contentW = containerW;
          }
          if (Math.abs(containerH - contentH) < 2) {
            contentH = containerH;
          }
          const 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;
        }
      }
      class EqualToFrame extends ContainerStrategy {
        constructor() {
          super();
          this.name = 'EqualToFrame';
        }
        apply(_view, designedResolution) {
          screenAdapter.isProportionalToFrame = false;
          this._setupCanvas();
        }
      }
      class ProportionalToFrame extends ContainerStrategy {
        constructor() {
          super();
          this.name = 'ProportionalToFrame';
        }
        apply(_view, designedResolution) {
          screenAdapter.isProportionalToFrame = true;
          this._setupCanvas();
        }
      }
      ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
      ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
      class ExactFit extends ContentStrategy {
        constructor() {
          super();
          this.name = 'ExactFit';
          this._strategy = ResolutionPolicy.EXACT_FIT;
        }
        apply(_view, designedResolution) {
          const windowSize = screen.windowSize;
          const containerW = windowSize.width;
          const containerH = windowSize.height;
          const scaleX = containerW / designedResolution.width;
          const scaleY = containerH / designedResolution.height;
          return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
        }
      }
      class ShowAll extends ContentStrategy {
        constructor() {
          super();
          this.name = 'ShowAll';
          this._strategy = ResolutionPolicy.SHOW_ALL;
        }
        apply(_view, designedResolution) {
          const windowSize = screen.windowSize;
          const containerW = windowSize.width;
          const containerH = windowSize.height;
          const designW = designedResolution.width;
          const designH = designedResolution.height;
          const scaleX = containerW / designW;
          const scaleY = containerH / designH;
          let scale = 0;
          let contentW;
          let 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);
        }
      }
      class NoBorder extends ContentStrategy {
        constructor() {
          super();
          this.name = 'NoBorder';
          this._strategy = ResolutionPolicy.NO_BORDER;
        }
        apply(_view, designedResolution) {
          const windowSize = screen.windowSize;
          const containerW = windowSize.width;
          const containerH = windowSize.height;
          const designW = designedResolution.width;
          const designH = designedResolution.height;
          const scaleX = containerW / designW;
          const scaleY = containerH / designH;
          let scale;
          let contentW;
          let 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);
        }
      }
      class FixedHeight extends ContentStrategy {
        constructor() {
          super();
          this.name = 'FixedHeight';
          this._strategy = ResolutionPolicy.FIXED_HEIGHT;
        }
        apply(_view, designedResolution) {
          const windowSize = screen.windowSize;
          const containerW = windowSize.width;
          const containerH = windowSize.height;
          const designH = designedResolution.height;
          const scale = containerH / designH;
          const contentW = containerW;
          const contentH = containerH;
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        }
      }
      class FixedWidth extends ContentStrategy {
        constructor() {
          super();
          this.name = 'FixedWidth';
          this._strategy = ResolutionPolicy.FIXED_WIDTH;
        }
        apply(_view, designedResolution) {
          const windowSize = screen.windowSize;
          const containerW = windowSize.width;
          const containerH = windowSize.height;
          const designW = designedResolution.width;
          const scale = containerW / designW;
          const contentW = containerW;
          const contentH = containerH;
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        }
      }
      class ResolutionPolicy {
        constructor(containerStg, contentStg) {
          this.name = 'ResolutionPolicy';
          this._containerStrategy = containerStg;
          this._contentStrategy = contentStg;
        }
        get canvasSize() {
          return screen.windowSize;
        }
        preApply(_view) {
          this._contentStrategy.preApply(_view);
        }
        apply(_view, designedResolution) {
          this._containerStrategy.apply(_view, designedResolution);
          return this._contentStrategy.apply(_view, designedResolution);
        }
        postApply(_view) {
          this._contentStrategy.postApply(_view);
        }
        setContainerStrategy(containerStg) {
          this._containerStrategy = containerStg;
        }
        setContentStrategy(contentStg) {
          this._contentStrategy = contentStg;
        }
        getContentStrategy() {
          return this._contentStrategy;
        }
      } exports("ResolutionPolicy", 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;
      cclegacy.ResolutionPolicy = ResolutionPolicy;
      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();
      const view = exports("view", View.instance = cclegacy.view = new View());
      director.registerSystem('view', view, 0);
      cclegacy.winSize = localWinSize;

      const v2_0 = new Vec2();
      class SplashScreen {
        get isFinished() {
          return this._curTime >= this.settings.totalTime;
        }
        set curTime(val) {
          this._curTime = val;
        }
        get curTime() {
          return this._curTime;
        }
        init() {
          var _policy, _settings$querySettin, _settings$querySettin2, _settings$querySettin3, _settings$querySettin4, _settings$querySettin5, _settings$querySettin6;
          let policy = ResolutionPolicy.SHOW_ALL;
          {
            const designResolution = settings.querySettings("screen", 'designResolution');
            if (designResolution !== null) {
              policy = designResolution.policy;
            }
          }
          this.settings = {
            policy: (_policy = policy) !== null && _policy !== void 0 ? _policy : ResolutionPolicy.SHOW_ALL,
            displayRatio: (_settings$querySettin = settings.querySettings("splashScreen", 'displayRatio')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : 0.4,
            totalTime: (_settings$querySettin2 = settings.querySettings("splashScreen", 'totalTime')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 3000,
            watermarkLocation: (_settings$querySettin3 = settings.querySettings("splashScreen", 'watermarkLocation')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 'default',
            autoFit: (_settings$querySettin4 = settings.querySettings("splashScreen", 'autoFit')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : true,
            logo: (_settings$querySettin5 = settings.querySettings("splashScreen", 'logo')) !== null && _settings$querySettin5 !== void 0 ? _settings$querySettin5 : undefined,
            background: (_settings$querySettin6 = settings.querySettings("splashScreen", '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 = cclegacy.director.root.device;
            this.swapchain = cclegacy.director.root.mainWindow.swapchain;
            this.preInit();
            this.initLayout();
            if (this.settings.logo.type === 'default') {
              this.initWaterMark();
            }
            let bgPromise = Promise.resolve();
            let logoPromise = Promise.resolve();
            if (this.settings.background.type === 'custom') {
              bgPromise = new Promise((resolve, reject) => {
                this.bgImage = new ccwindow$1.Image();
                this.bgImage.onload = () => {
                  this.initBG();
                  resolve();
                };
                this.bgImage.onerror = () => {
                  reject();
                };
                this.bgImage.src = this.settings.background.base64;
              });
            }
            if (this.settings.logo.type !== 'none') {
              logoPromise = new Promise((resolve, reject) => {
                this.logoImage = new ccwindow$1.Image();
                this.logoImage.onload = () => {
                  this.initLogo();
                  resolve();
                };
                this.logoImage.onerror = () => {
                  reject();
                };
                this.logoImage.src = this.settings.logo.base64;
              });
            }
            return Promise.all([bgPromise, logoPromise]);
          }
          return Promise.resolve([]);
        }
        preInit() {
          var _this$settings$backgr;
          const 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)];
          const {
            device,
            swapchain
          } = this;
          this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height);
          this.cmdBuff = device.commandBuffer;
          const 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]);
          const vbStride = 4 * 4;
          const vbSize = vbStride * 4;
          this.vertexBuffers = device.createBuffer(new BufferInfo(8 | 2, 1, vbSize, vbStride));
          this.vertexBuffers.update(verts);
          const indices = new Uint16Array([0, 1, 2, 1, 3, 2]);
          const ibStride = 2;
          const ibSize = ibStride * 6;
          this.indicesBuffers = device.createBuffer(new BufferInfo(4 | 2, 1, ibSize, ibStride));
          this.indicesBuffers.update(indices);
          const attributes = [new Attribute('a_position', 21), new Attribute('a_texCoord', 21)];
          const 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;
        }
        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();
        }
        initScale() {
          const dw = this.swapchain.width;
          const dh = this.swapchain.height;
          let desiredWidth = this.isMobile ? 375 : 1080;
          let desiredHeight = this.isMobile ? 812 : 1920;
          if (dw > dh) {
            const temp = desiredHeight;
            desiredHeight = desiredWidth;
            desiredWidth = temp;
          }
          if (dw / dh > 16 / 9) {
            this.scaleSize = dh / desiredHeight;
          } else {
            this.scaleSize = dw / desiredWidth;
          }
        }
        update(deltaTime) {
          const settings = this.settings;
          const {
            device,
            swapchain
          } = this;
          Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
          const dw = swapchain.width;
          const dh = swapchain.height;
          this.initScale();
          this._curTime += deltaTime * 1000;
          const percent = clamp01(this._curTime / settings.totalTime);
          const u_p = cubicOut(percent);
          let scaleX = 1;
          let scaleY = 1;
          if (this.settings.background.type === 'custom') {
            if (this.settings.policy === ResolutionPolicy.FIXED_WIDTH) {
              scaleX = dw;
              scaleY = dw / this.bgImage.width * this.bgImage.height;
            } else if (this.settings.policy === ResolutionPolicy.FIXED_HEIGHT) {
              scaleX = dh / this.bgImage.height * this.bgImage.width;
              scaleY = dh;
            } else if (this.settings.policy === ResolutionPolicy.SHOW_ALL) {
              if (this.bgImage.width / this.bgHeight > dw / dh) {
                scaleX = dw;
                scaleY = dw / this.bgImage.width * this.bgImage.height;
              } else {
                scaleX = dh / this.bgImage.height * this.bgImage.width;
                scaleY = dh;
              }
            } else if (this.settings.policy === ResolutionPolicy.NO_BORDER) {
              if (this.bgImage.width / this.bgImage.height > dw / dh) {
                scaleX = dh / this.bgImage.height * this.bgImage.width;
                scaleY = dh;
              } else {
                scaleX = dw;
                scaleY = dw / this.bgImage.width * this.bgImage.height;
              }
            } else {
              scaleX = dw;
              scaleY = dh;
            }
            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();
          }
          const logoYTrans = dh * this.logoYTrans;
          if (this.settings.logo.type !== 'none') {
            scaleY = dh * 0.185 * settings.displayRatio;
            scaleX = this.logoWidth * (dh * 0.185 / this.logoHeight) * 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) {
            const watermarkTW = this.watermarkTexture.width;
            const watermarkTH = this.watermarkTexture.height;
            scaleX = watermarkTW;
            scaleY = watermarkTH;
            const 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();
        }
        initBG() {
          const device = this.device;
          this.bgMat = new Material$1();
          this.bgMat.initialize({
            effectName: 'util/splash-screen'
          });
          const samplerInfo = new SamplerInfo();
          samplerInfo.addressU = 2;
          samplerInfo.addressV = 2;
          samplerInfo.addressW = 2;
          this.sampler = device.getSampler(samplerInfo);
          this.bgTexture = device.createTexture(new TextureInfo(1, 4 | 2, 35, this.bgImage.width, this.bgImage.height));
          const pass = this.bgMat.passes[0];
          const binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.bgTexture);
          this.shader = pass.getShaderVariant();
          const descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          const 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]);
        }
        initLogo() {
          const device = this.device;
          this.logoMat = new Material$1();
          this.logoMat.initialize({
            effectName: 'util/splash-screen'
          });
          const samplerInfo = new SamplerInfo();
          samplerInfo.addressU = 2;
          samplerInfo.addressV = 2;
          samplerInfo.addressW = 2;
          this.sampler = device.getSampler(samplerInfo);
          this.logoTexture = device.createTexture(new TextureInfo(1, 4 | 2, 35, this.logoImage.width, this.logoImage.height));
          const pass = this.logoMat.passes[0];
          const binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.logoTexture);
          this.shader = pass.getShaderVariant();
          const descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          const 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]);
          const 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;
          }
        }
        initWaterMark() {
          const watermarkImg = ccwindow$1.document.createElement('canvas');
          watermarkImg.height = this.textHeight * this.scaleSize;
          watermarkImg.style.width = `${watermarkImg.width}`;
          watermarkImg.style.height = `${watermarkImg.height}`;
          const text = 'Created with Cocos';
          const ctx = watermarkImg.getContext('2d');
          ctx.font = `${this.textSize * this.scaleSize}px Arial`;
          ctx.textBaseline = 'top';
          ctx.textAlign = 'center';
          ctx.fillStyle = '#707070';
          const 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);
          const region = new BufferTextureCopy();
          region.texExtent.width = watermarkImg.width;
          region.texExtent.height = watermarkImg.height;
          region.texExtent.depth = 1;
          this.watermarkTexture = this.device.createTexture(new TextureInfo(1, 4 | 2, 35, watermarkImg.width, watermarkImg.height));
          this.device.copyTexImagesToTexture([watermarkImg], this.watermarkTexture, [region]);
          this.watermarkMat = new Material$1();
          this.watermarkMat.initialize({
            effectName: 'util/splash-screen'
          });
          const pass = this.watermarkMat.passes[0];
          const binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.watermarkTexture);
          pass.descriptorSet.update();
        }
        frame() {
          const {
            device,
            swapchain
          } = this;
          if (!sys.isXR || xr.entry.isRenderAllowable()) {
            const renderSize = sys.isXR ? 2 : 1;
            for (let xrEye = 0; xrEye < renderSize; xrEye++) {
              if (sys.isXR) {
                xr.entry.renderLoopStart(xrEye);
                const xrFov = xr.entry.getEyeFov(xrEye);
                let radioLeft = 1.0;
                let radioRight = 1.0;
                if (xrEye === 0) {
                  radioLeft = Math.abs(Math.tan(xrFov[0])) / Math.abs(Math.tan(xrFov[1]));
                } else if (xrEye === 1) {
                  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]);
              const cmdBuff = this.cmdBuff;
              const framebuffer = cclegacy.director.root.mainWindow.framebuffer;
              const renderArea = this.renderArea;
              renderArea.width = swapchain.width;
              renderArea.height = swapchain.height;
              cmdBuff.begin();
              cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0);
              const pipeline = cclegacy.director.root.pipeline;
              if (this.settings.background.type === 'custom') {
                const bgPass = this.bgMat.passes[0];
                const bgPso = PipelineStateManager.getOrCreatePipelineState(device, bgPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(bgPso);
                cmdBuff.bindDescriptorSet(0, pipeline.descriptorSet);
                cmdBuff.bindDescriptorSet(1, bgPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type !== 'none') {
                const logoPass = this.logoMat.passes[0];
                const logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(logoPso);
                cmdBuff.bindDescriptorSet(0, pipeline.descriptorSet);
                cmdBuff.bindDescriptorSet(1, logoPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type === 'default' && this.watermarkMat) {
                const wartermarkPass = this.watermarkMat.passes[0];
                const watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(watermarkPso);
                cmdBuff.bindDescriptorSet(0, pipeline.descriptorSet);
                cmdBuff.bindDescriptorSet(1, 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);
              }
            }
          }
        }
        destroy() {
          this.device = null;
          this.swapchain = null;
          this.clearColors = null;
          if (this.bgImage) {
            if (this.bgImage.destroy) this.bgImage.destroy();
            this.bgImage = null;
          }
          if (this.bgMat) {
            this.bgMat.destroy();
            this.bgMat = null;
          }
          if (this.bgTexture) {
            this.bgTexture.destroy();
            this.bgTexture = null;
          }
          if (this.logoImage) {
            if (this.logoImage.destroy) this.logoImage.destroy();
            this.logoImage = null;
          }
          if (this.logoMat) {
            this.logoMat.destroy();
            this.logoMat = null;
          }
          if (this.logoTexture) {
            this.logoTexture.destroy();
            this.logoTexture = null;
          }
          this.renderArea = null;
          this.cmdBuff = null;
          this.shader = null;
          if (this.quadAssmebler) {
            this.quadAssmebler.destroy();
            this.quadAssmebler = null;
          }
          if (this.vertexBuffers) {
            this.vertexBuffers.destroy();
            this.vertexBuffers = null;
          }
          if (this.indicesBuffers) {
            this.indicesBuffers.destroy();
            this.indicesBuffers = null;
          }
          this.sampler = null;
          if (this.watermarkMat) {
            this.watermarkMat.destroy();
            this.watermarkMat = null;
          }
          if (this.watermarkTexture) {
            this.watermarkTexture.destroy();
            this.watermarkTexture = null;
          }
          this.settings = null;
        }
        static get instance() {
          return SplashScreen._ins;
        }
        static createInstance() {
          SplashScreen._ins = new SplashScreen();
          return SplashScreen._ins;
        }
        static releaseInstance() {
          if (SplashScreen._ins) {
            SplashScreen._ins.destroy();
            SplashScreen._ins = null;
          }
        }
        constructor() {
          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.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;
        }
      }
      SplashScreen._ins = null;
      cclegacy.internal.SplashScreen = SplashScreen;

      class EffectSettings {
        constructor() {
          this._data = null;
        }
        init(path = '') {
          if (!legacyCC.rendering || !legacyCC.rendering.enableEffectImport || !path) {
            return Promise.resolve();
          }
          return new Promise((resolve, reject) => {
            if (!path.startsWith('http')) {
              globalThis.fsUtils.readArrayBuffer(path, (err, arrayBuffer) => {
                if (err) {
                  reject(err);
                  return;
                }
                this._data = arrayBuffer;
                resolve();
              });
            } else {
              const xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'arraybuffer';
              xhr.onload = () => {
                this._data = xhr.response;
                resolve();
              };
              xhr.onerror = () => {
                reject(new Error('request effect settings failed!'));
              };
              xhr.send(null);
            }
          });
        }
        get data() {
          return this._data;
        }
      }
      const effectSettings = new EffectSettings();
      legacyCC.effectSettings = effectSettings;

      class Game extends EventTarget {
        constructor() {
          super();
          this.frame = null;
          this.container = null;
          this.canvas = null;
          this.renderType = -1;
          this.eventTargetOn = super.on;
          this.eventTargetOnce = super.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();
        }
        get inited() {
          return this._inited;
        }
        get frameRate() {
          return this._frameRate;
        }
        set frameRate(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;
        }
        get deltaTime() {
          return this._useFixedDeltaTime ? this.frameTime / 1000 : this._deltaTime;
        }
        get totalTime() {
          return performance.now() - this._initTime;
        }
        get frameStartTime() {
          return this._startTime;
        }
        setFrameRate(frameRate) {
          this.frameRate = frameRate;
        }
        getFrameRate() {
          return this.frameRate;
        }
        step() {
          director.tick(this._calculateDT(true));
        }
        pauseByEngine() {
          if (this._paused) {
            return;
          }
          this._pausedByEngine = true;
          this.pause();
        }
        resumeByEngine() {
          if (this._pausedByEngine) {
            this.resume();
            this._pausedByEngine = false;
          }
        }
        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);
        }
        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);
        }
        isPaused() {
          return this._paused;
        }
        restart() {
          const endFramePromise = new Promise(resolve => {
            director.once("director_end_frame", () => resolve());
          });
          return endFramePromise.then(() => {
            director.reset();
            cclegacy.Object._deferredDestroy();
            this.pause();
            this.resume();
            this._shouldLoadLaunchScene = true;
          }).then(() => {
            {
              return SplashScreen.createInstance().init();
            }
          }).then(() => {
            this._safeEmit(Game.EVENT_RESTART);
          });
        }
        end() {
          systemInfo.close();
        }
        on(type, callback, target, once) {
          if (this.canRegisterEvent(type)) {
            callback.call(target);
          }
          return this.eventTargetOn(type, callback, target, once);
        }
        once(type, callback, target) {
          if (this.canRegisterEvent(type)) {
            return callback.call(target);
          }
          return this.eventTargetOnce(type, callback, target);
        }
        canRegisterEvent(type) {
          return this._engineInited && type === Game.EVENT_ENGINE_INITED || this._inited && type === Game.EVENT_GAME_INITED || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED;
        }
        init(config) {
          this._compatibleWithOldParams(config);
          return Promise.resolve().then(() => {
            this.emit(Game.EVENT_PRE_BASE_INIT);
            return this.onPreBaseInitDelegate.dispatch();
          }).then(() => {
            {
              console.time('Init Base');
            }
            const debugMode = config.debugMode || 0;
            _resetDebugSetting(debugMode);
          }).then(() => sys.init()).then(() => {
            this._initEvents();
          }).then(() => settings.init(config.settingsPath, config.overrideSettings)).then(() => {
            {
              console.timeEnd('Init Base');
            }
            this.emit(Game.EVENT_POST_BASE_INIT);
            return this.onPostBaseInitDelegate.dispatch();
          }).then(() => {
            this.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT);
            return this.onPreInfrastructureInitDelegate.dispatch();
          }).then(() => {
            {
              console.time('Init Infrastructure');
            }
            macro.init();
            this._initXR();
            const adapter = findCanvas();
            if (adapter) {
              this.canvas = adapter.canvas;
              this.frame = adapter.frame;
              this.container = adapter.container;
            }
            screen.init();
            garbageCollectionManager.init();
            return deviceManager.init(this.canvas, bindingMappingInfo);
          }).then(() => {
            const usesCustomPipeline = settings.querySettings("rendering", 'customPipeline');
            if (usesCustomPipeline) {
              if (!cclegacy.rendering) {
                errorID(12109);
                return;
              }
              if (!macro.CUSTOM_PIPELINE_NAME) {
                macro.CUSTOM_PIPELINE_NAME = 'Builtin';
              }
            } else {
              cclegacy.rendering = undefined;
            }
            assetManager.init();
            builtinResMgr.init();
            Layers.init();
            this.initPacer();
            {
              console.timeEnd('Init Infrastructure');
            }
          }).then(() => {
            this.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT);
            return this.onPostInfrastructureInitDelegate.dispatch();
          }).then(() => {
            this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
            return this.onPreSubsystemInitDelegate.dispatch();
          }).then(() => effectSettings.init(settings.querySettings("rendering", 'effectSettingsPath'))).then(() => {
            if (!cclegacy.rendering || !cclegacy.rendering.enableEffectImport) {
              return;
            }
            const renderMode = settings.querySettings("rendering", 'renderMode');
            if (renderMode === 3) {
              cclegacy.rendering.init(deviceManager.gfxDevice, null);
              return;
            }
            const data = effectSettings.data;
            if (data === null) {
              errorID(1102);
              return;
            }
            cclegacy.rendering.init(deviceManager.gfxDevice, data);
          }).then(() => {
            const scriptPackages = settings.querySettings("scripting", 'scriptPackages');
            if (scriptPackages) {
              return Promise.all(scriptPackages.map(pack => module.import(pack)));
            }
            return Promise.resolve([]);
          }).then(() => {
            {
              console.time('Init SubSystem');
            }
            director.init();
            return builtinResMgr.loadBuiltinAssets();
          }).then(() => {
            {
              console.timeEnd('Init SubSystem');
            }
            this.emit(Game.EVENT_POST_SUBSYSTEM_INIT);
            return this.onPostSubsystemInitDelegate.dispatch();
          }).then(() => {
            log(`Cocos Creator v${engineVersion}`);
            this.emit(Game.EVENT_ENGINE_INITED);
            this._engineInited = true;
          }).then(() => {
            this.emit(Game.EVENT_PRE_PROJECT_INIT);
            return this.onPreProjectInitDelegate.dispatch();
          }).then(() => {
            {
              console.time('Init Project');
            }
            const jsList = settings.querySettings("plugins", 'jsList');
            let promise = Promise.resolve();
            if (jsList) {
              jsList.forEach(jsListFile => {
                promise = promise.then(() => loadJsFile(`${'src'}/${jsListFile}`));
              });
            }
            return promise;
          }).then(() => this._loadProjectBundles()).then(() => this._loadCCEScripts()).then(() => this._setupRenderPipeline()).then(() => this._loadPreloadAssets()).then(() => {
            builtinResMgr.compileBuiltinMaterial();
            return SplashScreen.createInstance().init();
          }).then(() => {
            {
              console.timeEnd('Init Project');
            }
            this.emit(Game.EVENT_POST_PROJECT_INIT);
            return this.onPostProjectInitDelegate.dispatch();
          }).then(() => {
            this._inited = true;
            this._safeEmit(Game.EVENT_GAME_INITED);
          });
        }
        _initXR() {
          var _settings$querySettin;
          if (typeof globalThis.__globalXR === 'undefined') {
            globalThis.__globalXR = {};
          }
          const globalXR = globalThis.__globalXR;
          globalXR.webxrCompatible = (_settings$querySettin = settings.querySettings("xr", 'webxrCompatible')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : false;
          if (sys.isXR) {
            var _settings$querySettin2, _settings$querySettin3;
            xr.entry = xr.XrEntry.getInstance();
            const xrMSAA = (_settings$querySettin2 = settings.querySettings("rendering", 'msaa')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 1;
            const xrRenderingScale = (_settings$querySettin3 = settings.querySettings("rendering", 'renderingScale')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 1.0;
            xr.entry.setMultisamplesRTT(xrMSAA);
            xr.entry.setRenderingScale(xrRenderingScale);
          }
        }
        _compatibleWithOldParams(config) {
          const 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;
          }
        }
        _loadPreloadAssets() {
          const preloadAssets = settings.querySettings("assets", 'preloadAssets');
          if (!preloadAssets) return Promise.resolve([]);
          return Promise.all(preloadAssets.map(uuid => new Promise((resolve, reject) => {
            assetManager.loadAny(uuid, err => {
              if (err) {
                reject(err);
                return;
              }
              resolve();
            });
          })));
        }
        _loadCCEScripts() {
          return new Promise((resolve, reject) => {
            {
              resolve();
            }
          });
        }
        _loadProjectBundles() {
          const preloadBundles = settings.querySettings("assets", 'preloadBundles');
          if (!preloadBundles) return Promise.resolve([]);
          return Promise.all(preloadBundles.map(({
            bundle,
            version
          }) => new Promise((resolve, reject) => {
            const opts = {};
            if (version) opts.version = version;
            assetManager.loadBundle(bundle, opts, err => {
              if (err) {
                reject(err);
                return;
              }
              resolve();
            });
          })));
        }
        run(onStart) {
          if (onStart) {
            this.onStart = onStart;
          }
          if (!this._inited || EDITOR_NOT_IN_PREVIEW) {
            return;
          }
          this.resume();
        }
        _calculateDT(useFixedDeltaTime) {
          this._useFixedDeltaTime = useFixedDeltaTime;
          if (useFixedDeltaTime) {
            this._startTime = performance.now();
            return this.frameTime / 1000;
          }
          const 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;
        }
        _updateCallback() {
          if (!this._inited) return;
          if (SplashScreen.instance && !SplashScreen.instance.isFinished) {
            SplashScreen.instance.update(this._calculateDT(false));
          } else if (this._shouldLoadLaunchScene) {
            {
              SplashScreen.releaseInstance();
            }
            this._shouldLoadLaunchScene = false;
            const launchScene = settings.querySettings("launch", 'launchScene');
            if (launchScene) {
              director.loadScene(launchScene, () => {
                var _this$onStart;
                logID(1103, launchScene);
                this._initTime = performance.now();
                director.startAnimation();
                (_this$onStart = this.onStart) === null || _this$onStart === void 0 ? void 0 : _this$onStart.call(this);
              });
            } else {
              var _this$onStart2;
              this._initTime = performance.now();
              director.startAnimation();
              (_this$onStart2 = this.onStart) === null || _this$onStart2 === void 0 ? void 0 : _this$onStart2.call(this);
            }
          } else {
            director.tick(this._calculateDT(false));
          }
        }
        initPacer() {
          var _settings$querySettin4;
          const frameRate = (_settings$querySettin4 = settings.querySettings("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;
        }
        _initEvents() {
          systemInfo.on('show', this._onShow, this);
          systemInfo.on('hide', this._onHide, this);
          systemInfo.on('close', this._onClose, this);
        }
        _onHide() {
          this.emit(Game.EVENT_HIDE);
          this.pauseByEngine();
        }
        _onShow() {
          this.emit(Game.EVENT_SHOW);
          this.resumeByEngine();
        }
        _onClose() {
          this.emit(Game.EVENT_CLOSE);
          systemInfo.exit();
        }
        addPersistRootNode(node) {
          director.addPersistRootNode(node);
        }
        removePersistRootNode(node) {
          director.removePersistRootNode(node);
        }
        isPersistRootNode(node) {
          return director.isPersistRootNode(node);
        }
        _setupRenderPipeline() {
          const usesCustomPipeline = settings.querySettings("rendering", 'customPipeline');
          return this._setRenderPipeline(!!usesCustomPipeline);
        }
        _setRenderPipeline(customPipeline) {
          if (!director.root.setRenderPipeline(customPipeline)) {
            errorID(1222);
            return;
          }
          this._rendererInitialized = true;
          this._safeEmit(Game.EVENT_RENDERER_INITED);
        }
        _safeEmit(event) {
          {
            this.emit(event);
          }
        }
      } exports("Game", Game);
      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;
      cclegacy.Game = Game;
      const game = exports("game", cclegacy.game = new Game());

      markAsWarning(Director.prototype, 'director', [{
        name: 'calculateDeltaTime'
      }, {
        name: 'getDeltaTime',
        suggest: 'Use game.deltaTime instead'
      }, {
        name: 'getTotalTime',
        suggest: 'Use game.totalTime instead'
      }, {
        name: 'getCurrentTime',
        suggest: 'Use game.frameStartTime instead'
      }]);
      removeProperty(Director.prototype, 'director', [{
        name: 'setAnimationInterval',
        suggest: 'please use game.frameRate instead'
      }, {
        name: 'getAnimationInterval',
        suggest: 'please use game.frameRate instead'
      }, {
        name: 'getRunningScene',
        suggest: 'please use getScene instead'
      }, {
        name: 'setDepthTest',
        suggest: 'please use camera API instead'
      }, {
        name: 'setClearColor',
        suggest: 'please use camera API instead'
      }, {
        name: 'getWinSize',
        suggest: 'please use view.getVisibleSize instead'
      }, {
        name: 'getWinSizeInPixels'
      }, {
        name: 'purgeCachedData',
        suggest: 'please use assetManager.releaseAll instead'
      }, {
        name: 'convertToGL'
      }, {
        name: 'convertToUI'
      }]);
      replaceProperty(director, 'director', [{
        name: '_getSceneUuid',
        targetName: 'assetManager.main',
        newName: 'getSceneInfo',
        customFunction: sceneName => {
          if (assetManager.main) {
            var _assetManager$main$ge;
            return (_assetManager$main$ge = assetManager.main.getSceneInfo(sceneName)) === null || _assetManager$main$ge === void 0 ? void 0 : _assetManager$main$ge.uuid;
          }
          return '';
        }
      }]);
      markAsWarning(game, 'game', [{
        name: 'collisionMatrix'
      }, {
        name: 'groupList'
      }]);
      replaceProperty(game, 'game', [{
        name: '_sceneInfos',
        targetName: 'assetManager.main',
        newName: 'getSceneInfo',
        customGetter: () => {
          const scenes = [];
          if (assetManager.main) {
            assetManager.main.config.scenes.forEach(val => {
              scenes.push(val);
            });
          }
          return scenes;
        }
      }]);

      class DynamicAtlasManager extends System {
        constructor() {
          super();
          this._atlases = [];
          this._atlasIndex = -1;
          this._maxAtlasCount = 5;
          this._textureSize = 2048;
          this._maxFrameSize = 512;
          this._textureBleeding = true;
          this._enabled = false;
        }
        get enabled() {
          return this._enabled;
        }
        set enabled(value) {
          if (this._enabled === value) return;
          if (value) {
            this.reset();
            director.on("director_before_scene_launch", this.beforeSceneLoad, this);
          } else {
            this.reset();
            director.off("director_before_scene_launch", this.beforeSceneLoad, this);
          }
          this._enabled = value;
        }
        get maxAtlasCount() {
          return this._maxAtlasCount;
        }
        set maxAtlasCount(value) {
          this._maxAtlasCount = value;
        }
        get atlasCount() {
          return this._atlases.length;
        }
        get textureBleeding() {
          return this._textureBleeding;
        }
        set textureBleeding(enable) {
          this._textureBleeding = enable;
        }
        get textureSize() {
          return this._textureSize;
        }
        set textureSize(value) {
          this._textureSize = value;
        }
        get maxFrameSize() {
          return this._maxFrameSize;
        }
        set maxFrameSize(value) {
          this._maxFrameSize = value;
        }
        newAtlas() {
          let atlas = this._atlases[++this._atlasIndex];
          if (!atlas && this._atlasIndex < this.maxAtlasCount) {
            atlas = new Atlas(this._textureSize, this._textureSize);
            this._atlases.push(atlas);
          }
          return atlas;
        }
        beforeSceneLoad() {
          this.reset();
        }
        init() {
          this.enabled = !macro.CLEANUP_IMAGE_CACHE;
        }
        insertSpriteFrame(spriteFrame) {
          if (!this._enabled || this._atlasIndex >= this._maxAtlasCount || !spriteFrame || spriteFrame.original) return null;
          if (!spriteFrame.packable) return null;
          const sampler = spriteFrame.texture.getSamplerInfo();
          if (sampler.minFilter !== 2 || sampler.magFilter !== 2 || sampler.mipFilter !== 0) {
            return null;
          }
          let atlas = this._atlases[this._atlasIndex];
          if (!atlas) {
            atlas = this.newAtlas();
          }
          const frame = atlas ? atlas.insertSpriteFrame(spriteFrame) : null;
          if (!frame && this._atlasIndex < this._maxAtlasCount) {
            atlas = this.newAtlas();
            return atlas ? atlas.insertSpriteFrame(spriteFrame) : null;
          }
          return frame;
        }
        reset() {
          for (let i = 0, l = this._atlases.length; i < l; i++) {
            this._atlases[i].destroy();
          }
          this._atlases.length = 0;
          this._atlasIndex = -1;
        }
        deleteAtlasSpriteFrame(spriteFrame) {
          if (!spriteFrame.original) return;
          let atlas;
          for (let i = this._atlases.length - 1; i >= 0; i--) {
            atlas = this._atlases[i];
            atlas.removeSpriteFrame(spriteFrame);
          }
          const texture = spriteFrame.original._texture;
          this.deleteAtlasTexture(texture);
        }
        deleteAtlasTexture(texture) {
          if (texture) {
            for (let 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--;
              }
            }
          }
        }
        packToDynamicAtlas(comp, frame) {
          if (!this._enabled) return;
          if (frame && !frame.original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) {
            const packedFrame = this.insertSpriteFrame(frame);
            if (packedFrame) {
              frame._setDynamicAtlasFrame(packedFrame);
            }
          }
        }
      } exports("DynamicAtlasManager", DynamicAtlasManager);
      DynamicAtlasManager.instance = void 0;
      const dynamicAtlasManager = exports("dynamicAtlasManager", DynamicAtlasManager.instance = new DynamicAtlasManager());
      director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0);
      cclegacy.internal.dynamicAtlasManager = dynamicAtlasManager;

      const _typeMap = {
        [1]: 'Uint',
        [2]: 'Int',
        [3]: 'Uint',
        [4]: 'Int',
        [5]: 'Float',
        [6]: 'Float',
        default: 'Uint'
      };
      function _getDataViewType(info) {
        const type = _typeMap[info.type] || _typeMap.default;
        const bytes = info.size / info.count * 8;
        return `${type}${bytes}`;
      }
      function writeBuffer(target, data, format = 11, offset = 0, stride = 0) {
        const info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        const writer = `set${_getDataViewType(info)}`;
        const componentBytesLength = info.size / info.count;
        const nSeg = Math.floor(data.length / info.count);
        const isLittleEndian = sys.isLittleEndian;
        for (let iSeg = 0; iSeg < nSeg; ++iSeg) {
          const x = offset + stride * iSeg;
          for (let iComponent = 0; iComponent < info.count; ++iComponent) {
            const y = x + componentBytesLength * iComponent;
            target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian);
          }
        }
      }
      function readBuffer(target, format = 11, offset = 0, length = target.byteLength - offset, stride = 0, out = []) {
        const info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        const reader = `get${_getDataViewType(info)}`;
        const componentBytesLength = info.size / info.count;
        const nSeg = Math.floor(length / stride);
        const isLittleEndian = sys.isLittleEndian;
        for (let iSeg = 0; iSeg < nSeg; ++iSeg) {
          const x = offset + stride * iSeg;
          for (let iComponent = 0; iComponent < info.count; ++iComponent) {
            const y = x + componentBytesLength * iComponent;
            out[info.count * iSeg + iComponent] = target[reader](y, isLittleEndian);
          }
        }
        return out;
      }
      function mapBuffer(target, callback, format = 11, offset = 0, length = target.byteLength - offset, stride = 0, out) {
        if (!out) {
          out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength));
        }
        const info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        const writer = `set${_getDataViewType(info)}`;
        const reader = `get${_getDataViewType(info)}`;
        const componentBytesLength = info.size / info.count;
        const nSeg = Math.floor(length / stride);
        const isLittleEndian = sys.isLittleEndian;
        for (let iSeg = 0; iSeg < nSeg; ++iSeg) {
          const x = offset + stride * iSeg;
          for (let iComponent = 0; iComponent < info.count; ++iComponent) {
            const y = x + componentBytesLength * iComponent;
            const cur = target[reader](y, isLittleEndian);
            out[writer](y, callback(cur, iComponent, target), isLittleEndian);
          }
        }
        return out;
      }

      const MeshUtils = jsb.MeshUtils;
      const createMesh = MeshUtils.createMesh;
      MeshUtils.createDynamicMesh;
      cclegacy.MeshUtils = jsb.MeshUtils;

      var _dec$2e, _class$2d, _class2$1S;
      const INSET_LEFT = 0;
      const INSET_TOP = 1;
      const INSET_RIGHT = 2;
      const INSET_BOTTOM = 3;
      const temp_vec3 = v3();
      const temp_matrix = mat4();
      const MeshType = {
        "RECT": 0,
        "POLYGON": 1
      };
      const temp_uvs = [{
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }];
      const SpriteFrameEvent = exports("SpriteFrameEvent", {
        "UV_UPDATED": "uv_updated"
      });
      let SpriteFrame = exports("SpriteFrame", (_dec$2e = ccclass$H('cc.SpriteFrame'), _dec$2e(_class$2d = (_class2$1S = class SpriteFrame extends Asset {
        static createWithImage(imageSourceOrImageAsset) {
          const img = imageSourceOrImageAsset instanceof ImageAsset$1 ? imageSourceOrImageAsset : new ImageAsset$1(imageSourceOrImageAsset);
          const tex = new Texture2D$1();
          tex.image = img;
          const spf = new SpriteFrame();
          spf.texture = tex;
          return spf;
        }
        get insetTop() {
          return this._capInsets[INSET_TOP];
        }
        set insetTop(value) {
          if (this._capInsets[INSET_TOP] === value) {
            return;
          }
          this._capInsets[INSET_TOP] = value;
          if (this._texture) {
            this._calculateSlicedUV();
          }
        }
        get insetBottom() {
          return this._capInsets[INSET_BOTTOM];
        }
        set insetBottom(value) {
          if (this._capInsets[INSET_BOTTOM] === value) {
            return;
          }
          this._capInsets[INSET_BOTTOM] = value;
          if (this._texture) {
            this._calculateSlicedUV();
          }
        }
        get insetLeft() {
          return this._capInsets[INSET_LEFT];
        }
        set insetLeft(value) {
          if (this._capInsets[INSET_LEFT] === value) {
            return;
          }
          this._capInsets[INSET_LEFT] = value;
          if (this._texture) {
            this._calculateSlicedUV();
          }
        }
        get insetRight() {
          return this._capInsets[INSET_RIGHT];
        }
        set insetRight(value) {
          if (this._capInsets[INSET_RIGHT] === value) {
            return;
          }
          this._capInsets[INSET_RIGHT] = value;
          if (this._texture) {
            this._calculateSlicedUV();
          }
        }
        get rect() {
          return this._rect;
        }
        set rect(value) {
          if (this._rect.equals(value)) {
            return;
          }
          this._rect.set(value);
          if (this._texture) {
            this._calculateUV();
          }
          this._calcTrimmedBorder();
        }
        get originalSize() {
          return this._originalSize;
        }
        set originalSize(value) {
          if (this._originalSize.equals(value)) {
            return;
          }
          this._originalSize.set(value);
          if (this._texture) {
            this._calculateUV();
          }
          this._calcTrimmedBorder();
        }
        get offset() {
          return this._offset;
        }
        set offset(value) {
          this._offset.set(value);
          this._calcTrimmedBorder();
        }
        get rotated() {
          return this._rotated;
        }
        set rotated(rotated) {
          if (this._rotated === rotated) {
            return;
          }
          this._rotated = rotated;
          if (this._texture) {
            this._calculateUV();
          }
        }
        get texture() {
          return this._texture;
        }
        set texture(value) {
          if (!value) {
            warnID(3122, this.name);
            return;
          }
          if (value === this._texture) {
            return;
          }
          this.reset({
            texture: value
          }, true);
        }
        get atlasUuid() {
          return this._atlasUuid;
        }
        set atlasUuid(value) {
          this._atlasUuid = value;
        }
        get width() {
          return this._texture.width;
        }
        get height() {
          return this._texture.height;
        }
        set _textureSource(value) {
          if (globalThis.Build) {
            this._texture = value;
            return;
          }
          if (value) {
            this._refreshTexture(value);
            this._calculateUV();
          }
        }
        get flipUVX() {
          return this._isFlipUVX;
        }
        set flipUVX(value) {
          this._isFlipUVX = value;
          this._calculateUV();
        }
        get flipUVY() {
          return this._isFlipUVY;
        }
        set flipUVY(value) {
          this._isFlipUVY = value;
          this._calculateUV();
        }
        get packable() {
          return this._packable;
        }
        set packable(value) {
          this._packable = value;
        }
        get original() {
          return this._original;
        }
        get pixelsToUnit() {
          return this._pixelsToUnit;
        }
        get pivot() {
          return this._pivot;
        }
        get mesh() {
          return this._mesh;
        }
        get trimmedBorder() {
          return this._trimmedBorder;
        }
        constructor() {
          super();
          this.vertices = null;
          this.uv = [];
          this.unbiasUV = [];
          this.uvSliced = [];
          this._rect = rect();
          this._trimmedBorder = v4();
          this._offset = v2$1();
          this._originalSize = size();
          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 = v2$1(0.5, 0.5);
          this._meshType = 0;
          this._extrude = 0;
          this._customOutLine = [];
          this._mesh = null;
          this._minPos = v3();
          this._maxPos = v3();
        }
        textureLoaded() {
          return !!this.texture;
        }
        isRotated() {
          return this._rotated;
        }
        setRotated(rotated) {
          this.rotated = rotated;
        }
        getRect(out) {
          if (out) {
            out.set(this._rect);
            return out;
          }
          return this._rect.clone();
        }
        setRect(rect) {
          this.rect = rect;
        }
        getOriginalSize(out) {
          if (out) {
            out.set(this._originalSize);
            return out;
          }
          return this._originalSize.clone();
        }
        setOriginalSize(size) {
          this.originalSize = size;
        }
        getOffset(out) {
          if (out) {
            out.set(this._offset);
            return out;
          }
          return this._offset.clone();
        }
        setOffset(offset) {
          this.offset = offset;
        }
        getGFXTexture() {
          return this._texture.getGFXTexture();
        }
        getGFXSampler() {
          return this._texture.getGFXSampler();
        }
        getHash() {
          return this._texture.getHash();
        }
        getSamplerInfo() {
          return this._texture.getSamplerInfo();
        }
        reset(info, clearData = false) {
          let 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();
        }
        checkRect(texture) {
          const rect = this._rect;
          let maxX = rect.x;
          let 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;
        }
        _calcTrimmedBorder() {
          const ow = this._originalSize.width;
          const oh = this._originalSize.height;
          const rw = this._rect.width;
          const rh = this._rect.height;
          const halfTrimmedWidth = (ow - rw) * 0.5;
          const 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;
        }
        ensureMeshData() {
          if (this._mesh) return;
          this._initVertices();
          this._createMesh();
        }
        destroy() {
          if (this._packable && dynamicAtlasManager) {
            dynamicAtlasManager.deleteAtlasSpriteFrame(this);
          }
          return super.destroy();
        }
        _calculateSlicedUV() {
          const rect = this._rect;
          const tex = this.texture;
          const atlasWidth = tex.width;
          const atlasHeight = tex.height;
          const leftWidth = this._capInsets[INSET_LEFT];
          const rightWidth = this._capInsets[INSET_RIGHT];
          const centerWidth = rect.width - leftWidth - rightWidth;
          const topHeight = this._capInsets[INSET_TOP];
          const bottomHeight = this._capInsets[INSET_BOTTOM];
          const centerHeight = rect.height - topHeight - bottomHeight;
          const 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 (let row = 0; row < 4; ++row) {
              const rowD = temp_uvs[row];
              for (let col = 0; col < 4; ++col) {
                const 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 (let row = 0; row < 4; ++row) {
              const rowD = temp_uvs[row];
              for (let col = 0; col < 4; ++col) {
                const colD = temp_uvs[col];
                uvSliced.push({
                  u: colD.u,
                  v: rowD.v
                });
              }
            }
          }
          this.emit("uv_updated", this);
        }
        _calculateUV() {
          const rect = this._rect;
          const uv = this.uv;
          const unbiasUV = this.unbiasUV;
          const tex = this.texture;
          const texw = tex.width;
          const texh = tex.height;
          if (this._rotated) {
            const l = texw === 0 ? 0 : rect.x / texw;
            const r = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            const t = texh === 0 ? 0 : rect.y / texh;
            const 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;
            }
            const ul = texw === 0 ? 0 : rect.x / texw;
            const ur = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            const ut = texh === 0 ? 0 : rect.y / texh;
            const 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 {
            const l = texw === 0 ? 0 : rect.x / texw;
            const r = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            const b = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            const 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;
            }
            const ul = texw === 0 ? 0 : rect.x / texw;
            const ur = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            const ub = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            const 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();
        }
        _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();
        }
        _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();
        }
        _checkPackable() {
          const dynamicAtlas = dynamicAtlasManager;
          if (!dynamicAtlas) return;
          const texture = this._texture;
          if (!(texture instanceof Texture2D$1) || texture.isCompressed) {
            this._packable = false;
            return;
          }
          const w = this.width;
          const h = this.height;
          if (!texture.image || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize) {
            this._packable = false;
            return;
          }
          const CanvasElement = ccwindow$1.HTMLCanvasElement;
          if (texture.image && texture.image instanceof CanvasElement) {
            this._packable = true;
          }
        }
        _serialize(ctxForExporting) {
          return null;
        }
        _deserialize(serializeData, handle) {
          const data = serializeData;
          const rect = data.rect;
          if (rect) {
            this._rect = new Rect$1(rect.x, rect.y, rect.width, rect.height);
          }
          const offset = data.offset;
          if (data.offset) {
            this._offset = v2$1(offset.x, offset.y);
          }
          const originalSize = data.originalSize;
          if (data.originalSize) {
            this._originalSize = size(originalSize.width, originalSize.height);
          }
          this._rotated = !!data.rotated;
          this._name = data.name;
          this._packable = !!data.packable;
          this._pixelsToUnit = data.pixelsToUnit;
          const pivot = data.pivot;
          if (pivot) {
            this._pivot = v2$1(pivot.x, pivot.y);
          }
          this._meshType = data.meshType;
          const 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];
          }
          const vertices = data.vertices;
          if (vertices) {
            if (!this.vertices) {
              this.vertices = {
                rawPosition: [],
                positions: [],
                indexes: vertices.indexes,
                uv: vertices.uv,
                nuv: vertices.nuv,
                minPos: v3(vertices.minPos.x, vertices.minPos.y, vertices.minPos.z),
                maxPos: v3(vertices.maxPos.x, vertices.maxPos.y, vertices.maxPos.z)
              };
            }
            this.vertices.rawPosition.length = 0;
            const rawPosition = vertices.rawPosition;
            for (let i = 0; i < rawPosition.length; i += 3) {
              this.vertices.rawPosition.push(v3(rawPosition[i], rawPosition[i + 1], rawPosition[i + 2]));
            }
            this._updateMeshVertices();
          }
        }
        clone() {
          const sp = new SpriteFrame();
          const 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.maxPos.clone()
          } : null;
          sp.uv.splice(0, sp.uv.length, ...this.uv);
          sp.unbiasUV.splice(0, sp.unbiasUV.length, ...this.unbiasUV);
          sp.uvSliced.splice(0, sp.uvSliced.length, ...this.uvSliced);
          sp._rect.set(this._rect);
          sp._trimmedBorder.set(this._trimmedBorder);
          sp._offset.set(this._offset);
          sp._originalSize.set(this._originalSize);
          sp._rotated = this._rotated;
          sp._capInsets.splice(0, sp._capInsets.length, ...this._capInsets);
          sp._atlasUuid = this._atlasUuid;
          sp._texture = this._texture;
          sp._isFlipUVX = this._isFlipUVX;
          sp._isFlipUVY = this._isFlipUVY;
          if (this._original) {
            sp._original = {
              _texture: this._original._texture,
              _x: this._original._x,
              _y: this._original._y
            };
          } else {
            sp._original = null;
          }
          sp._packable = this._packable;
          sp._pixelsToUnit = this._pixelsToUnit;
          sp._pivot.set(this._pivot);
          sp._meshType = this._meshType;
          sp._extrude = this._extrude;
          sp._customOutLine.splice(0, sp._customOutLine.length, ...this._customOutLine);
          sp._minPos = this._minPos;
          sp._maxPos = this._maxPos;
          if (this._mesh) {
            sp._createMesh();
          }
          return sp;
        }
        _refreshTexture(texture) {
          this._texture = texture;
          const tex = this._texture;
          const config = {};
          let isReset = false;
          if (this._rect.width === 0 || this._rect.height === 0 || !this.checkRect(tex)) {
            config.rect = rect(0, 0, tex.width, tex.height);
            isReset = true;
          }
          if (this._originalSize.width === 0 || this._originalSize.height === 0 || isReset) {
            config.originalSize = size(tex.width, tex.height);
            isReset = true;
          }
          if (isReset) {
            this.reset(config);
          }
          this._checkPackable();
          if (this._mesh) {
            this._updateMesh();
          }
        }
        onLoaded() {
          this._calcTrimmedBorder();
        }
        initDefault(uuid) {
          super.initDefault(uuid);
          const texture = new Texture2D$1();
          texture.initDefault();
          this._refreshTexture(texture);
          this._calculateUV();
        }
        validate() {
          return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0;
        }
        _initVertices() {
          if (!this.vertices) {
            this.vertices = {
              rawPosition: [],
              positions: [],
              indexes: [],
              uv: [],
              nuv: [],
              minPos: v3(),
              maxPos: v3()
            };
          } 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 === 1) ; else {
            const tex = this.texture;
            const texw = tex.width;
            const texh = tex.height;
            const rect = this.rect;
            const width = rect.width;
            const height = rect.height;
            const rectX = rect.x;
            const rectY = texh - rect.y - height;
            const halfWidth = width / 2;
            const halfHeight = height / 2;
            const l = texw === 0 ? 0 : rectX / texw;
            const r = texw === 0 ? 1 : (rectX + width) / texw;
            const t = texh === 0 ? 1 : (rectY + height) / texh;
            const b = texh === 0 ? 0 : rectY / 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();
        }
        _updateMeshVertices() {
          temp_matrix.identity();
          const units = 1 / this._pixelsToUnit;
          const PosX = -(this._pivot.x - 0.5) * this.rect.width * units;
          const PosY = -(this._pivot.y - 0.5) * this.rect.height * units;
          const temp_vec3 = v3(PosX, PosY, 0);
          temp_matrix.transform(temp_vec3);
          temp_vec3.set(units, units, 1);
          temp_matrix.scale(temp_vec3);
          const vertices = this.vertices;
          for (let i = 0; i < vertices.rawPosition.length; i++) {
            const 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);
        }
        _createMesh() {
          this._mesh = createMesh({
            primitiveMode: 7,
            positions: this.vertices.positions,
            uvs: this.vertices.nuv,
            indices: this.vertices.indexes,
            minPos: this._minPos,
            maxPos: this._maxPos,
            attributes: [new Attribute("a_position", 32), new Attribute("a_texCoord", 21)]
          });
        }
        _updateMesh() {
          if (this._mesh) {
            this._mesh.destroy();
          }
          this._initVertices();
          this._createMesh();
        }
      }, _class2$1S.EVENT_UV_UPDATED = "uv_updated", _class2$1S.MeshType = MeshType, _class2$1S)) || _class$2d));
      cclegacy.SpriteFrame = SpriteFrame;

      const renderTextureProto = jsb.RenderTexture.prototype;
      const textureBaseProto = jsb.TextureBase.prototype;
      renderTextureProto.createNode = null;
      const RenderTexture = exports("RenderTexture", jsb.RenderTexture);
      RenderTexture.Filter = TextureFilter;
      RenderTexture.PixelFormat = PixelFormat;
      RenderTexture.WrapMode = WrapMode$1;
      renderTextureProto._serialize = function (ctxForExporting) {
        return {};
      };
      renderTextureProto._deserialize = function (serializedData, handle) {
        const data = serializedData;
        this._width = data.w;
        this._height = data.h;
        this._name = data.n;
        textureBaseProto._deserialize.call(this, data.base, handle);
      };
      const oldReadPixels = renderTextureProto.readPixels;
      renderTextureProto.readPixels = function readPixels(x, y, width, height, buffer) {
        x = x || 0;
        y = y || 0;
        width = width || this.width;
        height = height || this.height;
        let tmpBuffer = oldReadPixels.call(this, x, y, width, height);
        if (tmpBuffer.length == 0) {
          return null;
        }
        buffer = tmpBuffer;
        return buffer;
      };
      cclegacy.RenderTexture = jsb.RenderTexture;
      patch_cc_RenderTexture({
        RenderTexture
      });

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

      const RenderingSubMesh = exports("RenderingSubMesh", jsb.RenderingSubMesh);
      const renderingSubMeshProto = RenderingSubMesh.prototype;
      renderingSubMeshProto._ctor = function (vertexBuffers, attributes, primitiveMode, indexBuffer = null, indirectBuffer = null) {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._attributes = attributes;
        this._vertexBuffers = vertexBuffers;
        this._indexBuffer = indexBuffer;
        this._indirectBuffer = indirectBuffer;
      };
      Object.defineProperty(renderingSubMeshProto, 'geometricInfo', {
        configurable: true,
        enumerable: true,
        get() {
          let r = this.getGeometricInfo();
          if (!r.positions && !r.indices) {
            r.positions = new Float32Array();
            r.indices = new Uint8Array();
          }
          return r;
        }
      });
      Object.defineProperty(renderingSubMeshProto, 'attributes', {
        configurable: true,
        enumerable: true,
        get() {
          if (!this._attributes) {
            this._attributes = this.getAttributes();
          }
          return this._attributes;
        }
      });
      Object.defineProperty(renderingSubMeshProto, 'vertexBuffers', {
        configurable: true,
        enumerable: true,
        get() {
          if (!this._vertexBuffers) {
            this._vertexBuffers = this.getVertexBuffers();
          }
          return this._vertexBuffers;
        }
      });
      Object.defineProperty(renderingSubMeshProto, 'indexBuffer', {
        configurable: true,
        enumerable: true,
        get() {
          if (!this._indexBuffer) {
            this._indexBuffer = this.getIndexBuffer();
          }
          return this._indexBuffer;
        }
      });
      Object.defineProperty(renderingSubMeshProto, 'indirectBuffer', {
        configurable: true,
        enumerable: true,
        get() {
          if (!this._indirectBuffer) {
            this._indirectBuffer = this.getIndexBuffer();
          }
          return this._indirectBuffer;
        }
      });

      var _dec$2d, _class$2c, _class2$1R, _initializer$1L;
      let SpriteAtlas = exports("SpriteAtlas", (_dec$2d = ccclass$H('cc.SpriteAtlas'), _dec$2d(_class$2c = (_class2$1R = class SpriteAtlas extends Asset {
        constructor() {
          super();
          this.spriteFrames = _initializer$1L && _initializer$1L();
        }
        getTexture() {
          const keys = Object.keys(this.spriteFrames);
          if (keys.length > 0) {
            const spriteFrame = this.spriteFrames[keys[0]];
            return spriteFrame && spriteFrame.texture;
          } else {
            return null;
          }
        }
        getSpriteFrame(key) {
          const sf = this.spriteFrames[key];
          if (!sf) {
            return null;
          }
          if (!sf.name) {
            sf.name = key;
          }
          return sf;
        }
        getSpriteFrames() {
          const frames = [];
          const spriteFrames = this.spriteFrames;
          for (const key of Object.keys(spriteFrames)) {
            frames.push(spriteFrames[key]);
          }
          return frames;
        }
        _serialize(ctxForExporting) {
          return null;
        }
        _deserialize(serializeData, handle) {
          const data = serializeData;
          this._name = data.name;
          const frames = data.spriteFrames;
          this.spriteFrames = createMap();
          for (let i = 0; i < frames.length; i += 2) {
            handle.result.push(this.spriteFrames, frames[i], frames[i + 1], getClassId(SpriteFrame));
          }
        }
      }, (_initializer$1L = applyDecoratedInitializer(_class2$1R.prototype, "spriteFrames", [serializable$l], function () {
        return createMap();
      })), _class2$1R)) || _class$2c));
      cclegacy.SpriteAtlas = SpriteAtlas;

      var _dec$2c, _class$2b;
      let Font = exports("Font", (_dec$2c = ccclass$H('cc.Font'), _dec$2c(_class$2b = class Font extends Asset {}) || _class$2b));
      cclegacy.Font = Font;

      var _dec$2b, _class$2a, _class2$1Q, _initializer$1K;
      let TTFFont = exports("TTFFont", (_dec$2b = ccclass$H('cc.TTFFont'), _dec$2b(_class$2a = (_class2$1Q = class TTFFont extends Font {
        constructor() {
          super();
          this._fontFamily = _initializer$1K && _initializer$1K();
        }
        get _nativeAsset() {
          return this._fontFamily;
        }
        set _nativeAsset(value) {
          this._fontFamily = value || 'Arial';
        }
        get _nativeDep() {
          return {
            uuid: this._uuid,
            __nativeName__: this._native,
            ext: extname(this._native),
            __isNative__: true
          };
        }
        initDefault(uuid) {
          this._fontFamily = 'Arial';
          super.initDefault(uuid);
        }
      }, (_initializer$1K = applyDecoratedInitializer(_class2$1Q.prototype, "_fontFamily", [serializable$l], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$1Q.prototype, "_nativeAsset", [override$1, string], Object.getOwnPropertyDescriptor(_class2$1Q.prototype, "_nativeAsset"), _class2$1Q.prototype), _applyDecoratedDescriptor(_class2$1Q.prototype, "_nativeDep", [override$1], Object.getOwnPropertyDescriptor(_class2$1Q.prototype, "_nativeDep"), _class2$1Q.prototype)), _class2$1Q)) || _class$2a));
      cclegacy.TTFFont = TTFFont;

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

      const ccdocument$3 = ccwindow$1.document;
      let _canvasContext = null;
      let _intervalId = -1;
      const _testString = 'BES bswy:->@123\u4E01\u3041\u1101';
      const _fontFaces = Object.create(null);
      const _loadingFonts = [];
      const _timeout = 3000;
      const useNativeCheck = (() => {
        let nativeCheck;
        return () => {
          if (nativeCheck === undefined) {
            if ('FontFace' in ccwindow$1) {
              const match = /Gecko.*Firefox\/(\d+)/.exec(ccwindow$1.navigator.userAgent);
              const safari10Match = /OS X.*Version\/10\..*Safari/.exec(ccwindow$1.navigator.userAgent) && /Apple/.exec(ccwindow$1.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() {
        let allFontsLoaded = true;
        const now = Date.now();
        for (let i = _loadingFonts.length - 1; i >= 0; i--) {
          const fontLoadHandle = _loadingFonts[i];
          const fontFamily = fontLoadHandle.fontFamilyName;
          if (now - fontLoadHandle.startTime > _timeout) {
            warnID(4933, fontFamily);
            fontLoadHandle.onComplete(null, fontFamily);
            _loadingFonts.splice(i, 1);
            continue;
          }
          const oldWidth = fontLoadHandle.refWidth;
          const fontDesc = `40px ${fontFamily}`;
          _canvasContext.font = fontDesc;
          const 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) {
        const loader = new Promise((resolve, reject) => {
          const check = () => {
            const now = Date.now();
            if (now - start >= _timeout) {
              reject();
            } else {
              ccdocument$3.fonts.load(`40px ${font}`).then(fonts => {
                if (fonts.length >= 1) {
                  resolve();
                } else {
                  setTimeout(check, 100);
                }
              }, () => {
                reject();
              });
            }
          };
          check();
        });
        let timeoutId = null;
        const timer = new Promise((resolve, reject) => {
          timeoutId = setTimeout(reject, _timeout);
        });
        Promise.race([timer, loader]).then(() => {
          if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = null;
          }
          callback(null, font);
        }, () => {
          warnID(4933, font);
          callback(null, font);
        });
      }
      function loadFont(url, options, onComplete) {
        const fontFamilyName = getFontFamily(url);
        if (_fontFaces[fontFamilyName]) {
          onComplete(null, fontFamilyName);
          return;
        }
        if (!_canvasContext) {
          const labelCanvas = ccdocument$3.createElement('canvas');
          labelCanvas.width = 100;
          labelCanvas.height = 100;
          _canvasContext = labelCanvas.getContext('2d');
        }
        const fontDesc = `40px ${fontFamilyName}`;
        const fontStyle = ccdocument$3.createElement('style');
        fontStyle.type = 'text/css';
        let 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$3.body.appendChild(fontStyle);
        const preloadDiv = ccdocument$3.createElement('div');
        const divStyle = preloadDiv.style;
        divStyle.fontFamily = fontFamilyName;
        preloadDiv.innerHTML = '.';
        divStyle.position = 'absolute';
        divStyle.left = '-100px';
        divStyle.top = '-100px';
        ccdocument$3.body.appendChild(preloadDiv);
        if (useNativeCheck()) {
          nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
        } else {
          const refWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
          const fontLoadHandle = {
            fontFamilyName,
            refWidth,
            onComplete,
            startTime: Date.now()
          };
          _loadingFonts.push(fontLoadHandle);
          if (_intervalId === -1) {
            _intervalId = setInterval(checkFontLoaded, 100);
          }
        }
        _fontFaces[fontFamilyName] = fontStyle;
      }
      function getFontFamily(fontHandle) {
        const ttfIndex = fontHandle.lastIndexOf('.ttf');
        if (ttfIndex === -1) {
          return fontHandle;
        }
        const slashPos = fontHandle.lastIndexOf('/');
        let 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) {
        const 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
      });

      const eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
      const imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
      class HtmlTextParser {
        constructor() {
          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, '\'']);
        }
        parse(htmlString) {
          this._resultObjectArray.length = 0;
          this._stack.length = 0;
          let startIndex = 0;
          const length = htmlString.length;
          while (startIndex < length) {
            let tagEndIndex = htmlString.indexOf('>', startIndex);
            let tagBeginIndex = -1;
            if (tagEndIndex >= 0) {
              tagBeginIndex = htmlString.lastIndexOf('<', tagEndIndex);
              const 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 {
              let newStr = htmlString.substring(startIndex, tagBeginIndex);
              const 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;
        }
        _attributeToObject(attribute) {
          attribute = attribute.trim();
          const obj = {};
          let header = /^(color|size)(\s)*=/.exec(attribute);
          let tagName = '';
          let nextSpace = 0;
          let eventHandlerString = '';
          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) {
              eventHandlerString = attribute.substring(nextSpace + 1).trim();
              obj.event = this._processEventHandler(eventHandlerString);
            }
            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);
          let remainingArgument = '';
          let rightQuot = -1;
          if (header && header[0].length > 0) {
            tagName = header[0].trim();
            if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') {
              header = imageAttrReg.exec(attribute);
              let tagValue;
              let isValidImageTag = false;
              while (header) {
                attribute = attribute.substring(attribute.indexOf(header[0]));
                tagName = attribute.substr(0, header[0].length);
                const 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();
            const defaultOutlineObject = {
              color: '#ffffff',
              width: 1
            };
            if (attribute) {
              const outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
              header = outlineAttrReg.exec(attribute);
              let 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;
        }
        getRightQuotationIndex(remainingArgument) {
          let leftQuot = -1;
          let rightQuot = -1;
          const leftSingleQuot = remainingArgument.indexOf('\'');
          const leftDoubleQuot = remainingArgument.indexOf('"');
          const useSingleQuot = leftSingleQuot > -1 && (leftSingleQuot < leftDoubleQuot || leftDoubleQuot === -1);
          const 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;
        }
        _processEventHandler(eventString) {
          const obj = {};
          let index = 0;
          let isValidTag = false;
          let eventNames = eventRegx.exec(eventString);
          while (eventNames) {
            let eventName = eventNames[0];
            let 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 {
              const 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;
        }
        _addToStack(attribute) {
          const obj = this._attributeToObject(attribute);
          if (this._stack.length === 0) {
            this._stack.push(obj);
          } else {
            if (obj.isNewLine || obj.isImage) {
              return;
            }
            const previousTagObj = this._stack[this._stack.length - 1];
            for (const key in previousTagObj) {
              if (!obj[key]) {
                obj[key] = previousTagObj[key];
              }
            }
            this._stack.push(obj);
          }
        }
        _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
            });
          }
        }
        _escapeSpecialSymbol(str) {
          for (const symbolArr of this._specialSymbolArray) {
            const key = symbolArr[0];
            const value = symbolArr[1];
            str = str.replace(key, value);
          }
          return str;
        }
      } exports("HtmlTextParser", HtmlTextParser);

      var _dec$2a, _dec2$1y, _class3$A, _class4$o, _initializer$1J, _initializer2$1l, _initializer3$Z, _initializer4$S;
      class FontLetterDefinition {
        constructor() {
          this.u = 0;
          this.v = 0;
          this.w = 0;
          this.h = 0;
          this.offsetX = 0;
          this.offsetY = 0;
          this.valid = false;
          this.xAdvance = 0;
        }
      }
      class FontAtlas {
        constructor(texture) {
          this.letterDefinitions = {};
          this.texture = texture;
        }
        addLetterDefinitions(letter, letterDefinition) {
          this.letterDefinitions[letter] = letterDefinition;
        }
        cloneLetterDefinition() {
          const copyLetterDefinitions = {};
          for (const key of Object.keys(this.letterDefinitions)) {
            const value = new FontLetterDefinition();
            mixin(value, this.letterDefinitions[key]);
            copyLetterDefinitions[key] = value;
          }
          return copyLetterDefinitions;
        }
        getTexture() {
          return this.texture;
        }
        getLetter(key) {
          return this.letterDefinitions[key];
        }
        getLetterDefinitionForChar(char, labelInfo) {
          const key = getSymbolCodeAt(char, 0);
          const hasKey = Object.prototype.hasOwnProperty.call(this.letterDefinitions, key);
          let letter = null;
          if (hasKey) {
            letter = this.letterDefinitions[key];
          }
          return letter;
        }
        clear() {
          this.letterDefinitions = {};
        }
      }
      let BitmapFont = exports("BitmapFont", (_dec$2a = ccclass$H('cc.BitmapFont'), _dec2$1y = type$a(SpriteFrame), _dec$2a(_class3$A = (_class4$o = class BitmapFont extends Font {
        constructor() {
          super();
          this.fntDataStr = _initializer$1J && _initializer$1J();
          this.spriteFrame = _initializer2$1l && _initializer2$1l();
          this.fontSize = _initializer3$Z && _initializer3$Z();
          this.fntConfig = _initializer4$S && _initializer4$S();
        }
        onLoaded() {
          const spriteFrame = this.spriteFrame;
          if (!this.fontDefDictionary && spriteFrame) {
            this.fontDefDictionary = new FontAtlas(spriteFrame.texture);
          }
          const fntConfig = this.fntConfig;
          if (!fntConfig) {
            warnID(16376);
            return;
          }
          const fontDict = fntConfig.fontDefDictionary;
          for (const fontDef in fontDict) {
            const info = fontDict[fontDef];
            const letter = new FontLetterDefinition();
            const rect = info.rect;
            letter.offsetX = info.xOffset;
            letter.offsetY = info.yOffset;
            letter.w = rect.width;
            letter.h = rect.height;
            letter.u = rect.x;
            letter.v = rect.y;
            letter.valid = true;
            letter.xAdvance = info.xAdvance;
            this.fontDefDictionary.addLetterDefinitions(fontDef, letter);
          }
        }
      }, (_initializer$1J = applyDecoratedInitializer(_class4$o.prototype, "fntDataStr", [serializable$l], function () {
        return '';
      }), _initializer2$1l = applyDecoratedInitializer(_class4$o.prototype, "spriteFrame", [_dec2$1y], function () {
        return null;
      }), _initializer3$Z = applyDecoratedInitializer(_class4$o.prototype, "fontSize", [serializable$l], function () {
        return -1;
      }), _initializer4$S = applyDecoratedInitializer(_class4$o.prototype, "fntConfig", [serializable$l], function () {
        return null;
      })), _class4$o)) || _class3$A));
      cclegacy.BitmapFont = BitmapFont;

      var _dec$29, _class$29;
      let LabelAtlas = exports("LabelAtlas", (_dec$29 = ccclass$H('cc.LabelAtlas'), _dec$29(_class$29 = class LabelAtlas extends BitmapFont {}) || _class$29));
      cclegacy.LabelAtlas = LabelAtlas;

      let _canvasPool;
      class CanvasPool {
        constructor() {
          this.pool = [];
        }
        static getInstance() {
          if (!_canvasPool) {
            _canvasPool = new CanvasPool();
          }
          return _canvasPool;
        }
        get() {
          let data = this.pool.pop();
          if (!data) {
            const canvas = ccwindow$1.document.createElement('canvas');
            const context = canvas.getContext('2d');
            data = {
              canvas,
              context
            };
          }
          return data;
        }
        put(canvas) {
          if (this.pool.length >= macro.MAX_LABEL_CANVAS_POOL_SIZE) {
            return;
          }
          this.pool.push(canvas);
        }
      }
      const WHITE$1 = Color$1.WHITE.clone();
      const space = 0;
      const bleed = 2;
      const _backgroundStyle = `rgba(255, 255, 255, ${(1 / 255).toFixed(3)})`;
      const BASELINE_OFFSET = getBaselineOffset();
      class LetterTexture {
        constructor(char, labelInfo) {
          this.image = null;
          this.data = null;
          this.canvas = null;
          this.context = null;
          this.width = 0;
          this.height = 0;
          this.offsetY = 0;
          this.char = char;
          this.labelInfo = labelInfo;
          this.hash = `${getSymbolCodeAt(char, 0)}${labelInfo.hash}`;
        }
        updateRenderData() {
          this._updateProperties();
          this._updateTexture();
        }
        destroy() {
          this.image = null;
          CanvasPool.getInstance().put(this.data);
        }
        _updateProperties() {
          this.data = CanvasPool.getInstance().get();
          this.canvas = this.data.canvas;
          this.context = this.data.context;
          if (this.context) {
            const fontScale = this.labelInfo.fontScale;
            this.context.font = this.labelInfo.fontDesc;
            const width = safeMeasureText(this.context, this.char, this.labelInfo.fontDesc);
            const 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$1();
          }
          this.image.reset(this.canvas);
        }
        _updateTexture() {
          if (!this.context || !this.canvas) {
            return;
          }
          const context = this.context;
          const labelInfo = this.labelInfo;
          const width = this.canvas.width;
          const height = this.canvas.height;
          const 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, (w, m, n, u) => (+m * fontScale + (+n || 0) * fontScale).toString() + u);
          const fontSize = labelInfo.fontSize * fontScale;
          const startX = width / 2;
          const startY = height / 2 + fontSize * MIDDLE_RATIO + fontSize * BASELINE_OFFSET;
          const color = labelInfo.color;
          context.lineJoin = 'round';
          context.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${1})`;
          if (labelInfo.isOutlined) {
            const 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);
        }
      }
      class LetterRenderTexture extends Texture2D$1 {
        initWithSize(width, height, format = 35) {
          this.reset({
            width,
            height,
            format
          });
        }
        drawTextureAt(image, x, y) {
          const gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          const gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            warnID(16363);
            return;
          }
          const 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]);
        }
      }
      class LetterAtlas {
        get width() {
          return this._width;
        }
        get height() {
          return this._height;
        }
        constructor(width, height) {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this._width = 0;
          this._height = 0;
          this._halfBleed = 0;
          this._dirty = false;
          const 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_before_scene_launch", this.beforeSceneLoad, this);
        }
        insertLetterTexture(letterTexture) {
          const img = letterTexture.image;
          const device = director.root.device;
          if (!img || !this.fontDefDictionary || !device) {
            return null;
          }
          const width = img.width;
          const height = img.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;
          }
          if (!this.fontDefDictionary.texture) {
            return null;
          }
          const rt = this.fontDefDictionary.texture;
          rt.drawTextureAt(img, this._x, this._y);
          this._dirty = true;
          const letterDefinition = new FontLetterDefinition();
          letterDefinition.u = this._x + this._halfBleed;
          letterDefinition.v = this._y + this._halfBleed;
          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;
        }
        update() {
          if (!this._dirty) {
            return;
          }
          this._dirty = false;
        }
        reset() {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this.fontDefDictionary.clear();
        }
        destroy() {
          this.reset();
          const dict = this.fontDefDictionary;
          if (dict && dict.texture) {
            dict.texture.destroy();
            dict.texture = null;
          }
        }
        getTexture() {
          return this.fontDefDictionary.getTexture();
        }
        beforeSceneLoad() {
          this.clearAllCache();
        }
        clearAllCache() {
          this.destroy();
          const texture = new LetterRenderTexture();
          texture.initWithSize(this._width, this._height);
          this.fontDefDictionary.texture = texture;
        }
        getLetter(key) {
          return this.fontDefDictionary.letterDefinitions[key];
        }
        getLetterDefinitionForChar(char, labelInfo) {
          const hash = getSymbolCodeAt(char, 0) + labelInfo.hash;
          let letter = this.fontDefDictionary.letterDefinitions[hash];
          if (!letter) {
            const temp = new LetterTexture(char, labelInfo);
            temp.updateRenderData();
            letter = this.insertLetterTexture(temp);
            temp.destroy();
          }
          return letter;
        }
      }
      const 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) {
        const hashData = '';
        const color = labelInfo.color.toHEX();
        let out = '';
        if (labelInfo.isOutlined && labelInfo.margin > 0) {
          out = out + labelInfo.margin + labelInfo.out.toHEX();
        }
        return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out;
      }

      const vfmt = [new Attribute("a_position", 32)];
      const vfmtPosColor = [new Attribute("a_position", 32), new Attribute("a_color", 44)];
      const vfmtPosUvColor = [new Attribute("a_position", 32), new Attribute("a_texCoord", 21), new Attribute("a_color", 44)];
      const vfmtPosUvColor4B = [new Attribute("a_position", 32), new Attribute("a_texCoord", 21), new Attribute("a_color", 35, true)];
      const vfmtPosUvTwoColor = [new Attribute("a_position", 32), new Attribute("a_texCoord", 21), new Attribute("a_color", 44), new Attribute("a_color2", 44)];
      const vfmtPosUvTwoColor4B = [new Attribute("a_position", 32), new Attribute("a_texCoord", 21), new Attribute("a_color", 35, true), new Attribute("a_color2", 35, true)];
      function getComponentPerVertex(attrs) {
        let count = 0;
        for (let i = 0; i < attrs.length; i++) {
          const attr = attrs[i];
          const info = FormatInfos[attr.format];
          count += info.count;
        }
        return count;
      }
      function getAttributeStride(attrs) {
        let count = 0;
        for (let i = 0; i < attrs.length; i++) {
          const attr = attrs[i];
          const info = FormatInfos[attr.format];
          count += info.size;
        }
        return count;
      }
      cclegacy.internal.vfmtPosUvColor = vfmtPosUvColor;
      cclegacy.internal.vfmtPosUvTwoColor = vfmtPosUvTwoColor;
      cclegacy.internal.vfmtPosUvColor4B = vfmtPosUvColor4B;
      cclegacy.internal.vfmtPosUvTwoColor4B = vfmtPosUvTwoColor4B;

      var vertexFormat = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getAttributeStride: getAttributeStride,
        getComponentPerVertex: getComponentPerVertex,
        vfmt: vfmt,
        vfmtPosColor: vfmtPosColor,
        vfmtPosUvColor: vfmtPosUvColor,
        vfmtPosUvColor4B: vfmtPosUvColor4B,
        vfmtPosUvTwoColor: vfmtPosUvTwoColor,
        vfmtPosUvTwoColor4B: vfmtPosUvTwoColor4B
      });
      exports("UIVertexFormat", vertexFormat);

      const NativeRenderDrawInfo = n2d.RenderDrawInfo;
      n2d.Batcher2d;
      const NativeUIMeshBuffer = n2d.UIMeshBuffer;
      const NativeRenderEntity = n2d.RenderEntity;
      const NativeUIModelProxy = n2d.UIModelProxy;
      n2d.StencilManager;

      const IA_POOL_USED_SCALE = 1 / 2;
      class MeshBuffer {
        get attributes() {
          return this._attributes;
        }
        get vertexFormatBytes() {
          return this._vertexFormatBytes;
        }
        get byteOffset() {
          return this._byteOffset;
        }
        set byteOffset(val) {
          this._byteOffset = val;
          {
            this._sharedBuffer[0] = val;
          }
        }
        get vertexOffset() {
          return this._vertexOffset;
        }
        set vertexOffset(val) {
          this._vertexOffset = val;
          {
            this._sharedBuffer[1] = val;
          }
        }
        get indexOffset() {
          return this._indexOffset;
        }
        set indexOffset(val) {
          this._indexOffset = val;
          {
            this._sharedBuffer[2] = val;
          }
        }
        get dirty() {
          return this._dirty;
        }
        set dirty(val) {
          this._dirty = val;
          {
            this._sharedBuffer[3] = val ? 1 : 0;
          }
        }
        get floatsPerVertex() {
          return this._floatsPerVertex;
        }
        set floatsPerVertex(val) {
          this._floatsPerVertex = val;
        }
        get vData() {
          return this._vData;
        }
        set vData(val) {
          this._vData = val;
          {
            this._nativeObj.vData = val;
          }
        }
        get iData() {
          return this._iData;
        }
        set iData(val) {
          this._iData = val;
          {
            this._nativeObj.iData = val;
          }
        }
        get nativeObj() {
          return this._nativeObj;
        }
        get sharedBuffer() {
          return this._sharedBuffer;
        }
        initSharedBuffer() {
          {
            this._sharedBuffer = new Uint32Array(4);
          }
        }
        syncSharedBufferToNative() {
          {
            this._nativeObj.syncSharedBufferToNative(this._sharedBuffer);
          }
        }
        constructor() {
          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._nativeObj = new NativeUIMeshBuffer();
          }
          this.initSharedBuffer();
          this.syncSharedBufferToNative();
        }
        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));
          {
            this._nativeObj.initialize(attrs);
          }
        }
        reset() {
          this._nextFreeIAHandle = 0;
          this.dirty = false;
        }
        destroy() {
          this.reset();
          this._attributes = null;
          this._iaInfo = null;
          this.vData = null;
          this.iData = null;
          for (let i = 0; i < this._iaPool.length; ++i) {
            const 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;
        }
        setDirty() {
          this.dirty = true;
        }
        request(vertexCount, indexCount) {
          warnID(9002);
          return false;
        }
        requireFreeIA(device) {
          if (this._iaPool.length <= this._nextFreeIAHandle) {
            this._iaPool.push(this.createNewIA(device));
          }
          const ia = this._iaPool[this._nextFreeIAHandle++].ia;
          return ia;
        }
        recycleIA(ia) {
          const pool = this._iaPool;
          for (let i = 0; i < this._nextFreeIAHandle; ++i) {
            if (ia === pool[i].ia) {
              const iaRef = pool[i];
              pool[i] = pool[--this._nextFreeIAHandle];
              pool[this._nextFreeIAHandle] = iaRef;
              return;
            }
          }
        }
        checkCapacity(vertexCount, indexCount) {
          const maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex;
          const maxIndex = this.indexOffset + indexCount;
          if (maxVertex > this._initVDataCount || maxIndex > this._initIDataCount) {
            return false;
          }
          return true;
        }
        uploadBuffers() {
          if (this.byteOffset === 0 || !this._dirty) {
            return;
          }
          const iOS14 = sys.__isWebIOS14OrIPadOS14Env;
          const submitCount = iOS14 ? this._nextFreeIAHandle : 1;
          if (iOS14 && submitCount / this._iaPool.length < IA_POOL_USED_SCALE) {
            const count = submitCount / IA_POOL_USED_SCALE;
            const length = this._iaPool.length;
            for (let i = length - 1; i >= count; i--) {
              const 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;
          }
          const byteCount = this.byteOffset;
          const indexCount = this.indexOffset;
          for (let i = 0; i < submitCount; ++i) {
            const iaRef = this._iaPool[i];
            const verticesData = new Float32Array(this.vData.buffer, 0, byteCount >> 2);
            const indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
            const 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;
        }
        createNewIA(device) {
          let ia;
          let vertexBuffers;
          let indexBuffer;
          if (sys.__isWebIOS14OrIPadOS14Env || !this._iaPool[0]) {
            const vbStride = this._vertexFormatBytes = this._floatsPerVertex * 4;
            const ibStride = 2;
            const vertexBuffer = device.createBuffer(new BufferInfo(8 | 2, 2 | 1, vbStride, vbStride));
            indexBuffer = device.createBuffer(new BufferInfo(4 | 2, 2 | 1, 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,
            vertexBuffers,
            indexBuffer
          };
        }
      } exports("MeshBuffer", MeshBuffer);

      class BufferAccessor {
        get attributes() {
          return this._attributes;
        }
        get vertexFormatBytes() {
          return this._vertexFormatBytes;
        }
        get floatsPerVertex() {
          return this._floatsPerVertex;
        }
        constructor(device, attributes) {
          this._buffers = [];
          this._device = device;
          this._attributes = attributes;
          this._floatsPerVertex = getAttributeStride(attributes) >> 2;
          this._vertexFormatBytes = this._floatsPerVertex * 4;
        }
        initialize() {}
        reset() {}
        request(vertexCount = 4, indexCount = 6) {}
        appendBuffers(vertices, indices) {}
        uploadBuffers() {}
        destroy() {
          this._attributes.length = 0;
        }
      }

      const _entryPool = new Pool(() => ({
        offset: 0,
        length: 0
      }), 32);
      class StaticVBChunk {
        get ib() {
          return this._ib;
        }
        constructor(vertexAccessor, bufferId, meshBuffer, vertexOffset, vb, indexCount) {
          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));
        }
        setIndexBuffer(indices) {
          {
            assertIsTrue(indices.length === this.ib.length);
            for (let i = 0; i < indices.length; ++i) {
              const vid = indices[i];
              this._ib[i] = this.vertexOffset + vid;
            }
          }
        }
      }
      class StaticVBAccessor extends BufferAccessor {
        get id() {
          return this._id;
        }
        constructor(device, attributes, vCount, iCount) {
          super(device, attributes);
          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();
        }
        destroy() {
          for (let i = 0; i < this._buffers.length; ++i) {
            this._buffers[i].destroy();
            const freeList = this._freeLists[i];
            for (let j = 0; j < freeList.length; ++j) {
              _entryPool.free(freeList[j]);
            }
          }
          this._buffers.length = 0;
          this._freeLists.length = 0;
          super.destroy();
        }
        reset() {
          for (let i = 0; i < this._buffers.length; ++i) {
            const buffer = this._buffers[i];
            buffer.indexOffset = 0;
            buffer.reset();
          }
        }
        getVertexBuffer(bid) {
          return this._buffers[bid].vData;
        }
        getIndexBuffer(bid) {
          return this._buffers[bid].iData;
        }
        getMeshBuffer(bid) {
          return this._buffers[bid];
        }
        uploadBuffers() {
          for (let i = 0; i < this._buffers.length; ++i) {
            const firstEntry = this._freeLists[i][0];
            const buffer = this._buffers[i];
            if (!firstEntry || firstEntry.length < buffer.vData.byteLength) {
              buffer.uploadBuffers();
            }
          }
        }
        appendIndices(bufferId, indices) {
          const buf = this._buffers[bufferId];
          const iCount = indices.length;
          if (iCount) {
            const needLength = buf.indexOffset + indices.length;
            if (buf.iData.length < needLength) {
              const expansionLength = Math.floor(1.25 * needLength);
              const newIData = new Uint16Array(expansionLength);
              newIData.set(buf.iData);
              buf.iData = newIData;
            }
            buf.iData.set(indices, buf.indexOffset);
            buf.indexOffset += indices.length;
          }
        }
        allocateChunk(vertexCount, indexCount) {
          const byteLength = vertexCount * this.vertexFormatBytes;
          if (vertexCount > this._vCount || indexCount > this._iCount) {
            errorID(9004, byteLength);
            return null;
          }
          let buf = null;
          let freeList;
          let bid = 0;
          let eid = -1;
          let entry = null;
          for (let i = 0; i < this._buffers.length; ++i) {
            buf = this._buffers[i];
            freeList = this._freeLists[i];
            for (let 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) {
              eid = 0;
              entry = this._freeLists[bid][eid];
            }
          }
          if (entry) {
            const vertexOffset = entry.offset / this.vertexFormatBytes;
            assertIsTrue(Number.isInteger(vertexOffset));
            const 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 {
            return null;
          }
        }
        recycleChunk(chunk) {
          const freeList = this._freeLists[chunk.bufferId];
          const buf = this._buffers[chunk.bufferId];
          let offset = chunk.vertexOffset * this.vertexFormatBytes;
          let bytes = chunk.vb.byteLength;
          if (bytes === 0) return;
          let recycled = false;
          let i = 0;
          let prevEntry = null;
          let nextEntry = freeList[i];
          while (nextEntry && nextEntry.offset < offset) {
            prevEntry = nextEntry;
            nextEntry = freeList[++i];
          }
          if (prevEntry) {
            const 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) {
            const distance = nextEntry.offset - (offset + bytes);
            assertIsTrue(distance >= 0);
            if (distance === 0) {
              nextEntry.offset = offset;
              nextEntry.length += bytes;
            } else {
              const 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 {
            const newEntry = _entryPool.alloc();
            newEntry.offset = offset;
            newEntry.length = bytes;
            freeList.push(newEntry);
          }
        }
        _allocateChunkFromEntry(bid, eid, entry, bytes) {
          const remaining = entry.length - bytes;
          const offset = entry.offset + bytes;
          const 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;
          }
        }
        _allocateBuffer() {
          assertID(this._buffers.length === this._freeLists.length, 9003);
          const buffer = new MeshBuffer();
          const vFloatCount = this._vCount * this._floatsPerVertex;
          buffer.initialize(this._device, this._attributes, vFloatCount, this._iCount);
          this._buffers.push(buffer);
          const entry = _entryPool.alloc();
          entry.offset = 0;
          entry.length = buffer.vData.byteLength;
          const freeList = [entry];
          this._freeLists.push(freeList);
          const batcher = director.root.batcher2D;
          batcher.syncMeshBuffersToNative(this.id, this._buffers);
          return this._buffers.length - 1;
        }
        static generateID() {
          return StaticVBAccessor.ID_COUNT++;
        }
      }
      StaticVBAccessor.IB_SCALE = 4;
      StaticVBAccessor.ID_COUNT = 0;

      class RenderDrawInfo {
        constructor(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 = 0;
          this._subNode = null;
          this._render2dBuffer = null;
          this.init(nativeDrawInfo);
          const attrSharedBuffer = this._nativeObj.getAttrSharedBufferForJS();
          let offset = 0;
          this._uint8SharedBuffer = new Uint8Array(attrSharedBuffer, offset, 4);
          offset += 4 * 1;
          this._uint16SharedBuffer = new Uint16Array(attrSharedBuffer, offset, 2);
          offset += 2 * 2;
          this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, 5);
        }
        get nativeObj() {
          return this._nativeObj;
        }
        get render2dBuffer() {
          return this._render2dBuffer;
        }
        init(nativeDrawInfo) {
          {
            if (nativeDrawInfo) {
              this._nativeObj = nativeDrawInfo;
            }
            if (!this._nativeObj) {
              this._nativeObj = new NativeRenderDrawInfo();
            }
          }
        }
        clear() {
          this._bufferId = 0;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._vertDirty = false;
        }
        setAccId(accId) {
          {
            if (this._accId !== accId) {
              this._uint16SharedBuffer[1] = accId;
            }
          }
          this._accId = accId;
        }
        setBufferId(bufferId) {
          {
            if (this._bufferId !== bufferId) {
              this._uint16SharedBuffer[0] = bufferId;
              this._nativeObj.changeMeshBuffer();
            }
          }
          this._bufferId = bufferId;
        }
        setAccAndBuffer(accId, bufferId) {
          {
            if (this._accId !== accId || this._bufferId !== bufferId) {
              this._uint16SharedBuffer[1] = accId;
              this._uint16SharedBuffer[0] = bufferId;
              this._nativeObj.changeMeshBuffer();
            }
          }
          this._bufferId = bufferId;
          this._accId = accId;
        }
        setVertexOffset(vertexOffset) {
          this._vertexOffset = vertexOffset;
          {
            this._uint32SharedBuffer[0] = vertexOffset;
          }
        }
        setIndexOffset(indexOffset) {
          this._indexOffset = indexOffset;
          {
            this._uint32SharedBuffer[1] = indexOffset;
          }
        }
        setVB(vbBuffer) {
          {
            this._nativeObj.vbBuffer = vbBuffer;
          }
        }
        setIB(ibBuffer) {
          {
            this._nativeObj.ibBuffer = ibBuffer;
          }
        }
        setVData(vDataBuffer) {
          {
            this._nativeObj.vDataBuffer = vDataBuffer;
          }
        }
        setIData(iDataBuffer) {
          {
            this._nativeObj.iDataBuffer = iDataBuffer;
          }
        }
        setVBCount(vbCount) {
          {
            this._uint32SharedBuffer[2] = vbCount;
          }
          this._vbCount = vbCount;
        }
        setIBCount(ibCount) {
          {
            this._uint32SharedBuffer[3] = ibCount;
          }
        }
        setVertDirty(val) {
          {
            this._uint8SharedBuffer[1] = val ? 1 : 0;
          }
          this._vertDirty = val;
        }
        setDataHash(dataHash) {
          {
            this._uint32SharedBuffer[4] = dataHash;
          }
          this._dataHash = dataHash;
        }
        setIsMeshBuffer(isMeshBuffer) {
          {
            this._uint8SharedBuffer[2] = isMeshBuffer ? 1 : 0;
          }
          this._isMeshBuffer = isMeshBuffer;
        }
        setMaterial(material) {
          {
            if (this._material !== material) {
              this._nativeObj.material = material;
            }
          }
          this._material = material;
        }
        setTexture(texture) {
          {
            if (this._texture !== texture) {
              this._nativeObj.texture = texture;
            }
          }
          this._texture = texture;
        }
        setSampler(sampler) {
          {
            if (this._sampler !== sampler) {
              this._nativeObj.sampler = sampler;
            }
          }
          this._sampler = sampler;
        }
        setModel(model) {
          {
            if (this._model !== model) {
              this._nativeObj.model = model;
            }
          }
        }
        setDrawInfoType(drawInfoType) {
          {
            if (this._drawInfoType !== drawInfoType) {
              this._uint8SharedBuffer[0] = drawInfoType;
            }
          }
          this._drawInfoType = drawInfoType;
        }
        setSubNode(node) {
          {
            if (this._subNode !== node) {
              this._nativeObj.subNode = node;
            }
          }
          this._subNode = node;
        }
        setStride(stride) {
          {
            this._uint8SharedBuffer[3] = stride;
          }
          this._stride = stride;
        }
        initRender2dBuffer() {
          {
            this._render2dBuffer = new Float32Array(this._vbCount * this._stride);
            this._nativeObj.setRender2dBufferToNative(this._render2dBuffer);
          }
        }
        fillRender2dBuffer(vertexDataArr) {
          {
            if (!this._render2dBuffer) {
              return;
            }
            const fillLength = Math.min(this._vbCount, vertexDataArr.length);
            let bufferOffset = 0;
            for (let i = 0; i < fillLength; i++) {
              const temp = vertexDataArr[i];
              this._render2dBuffer[bufferOffset] = temp.x;
              this._render2dBuffer[bufferOffset + 1] = temp.y;
              this._render2dBuffer[bufferOffset + 2] = temp.z;
              bufferOffset += this._stride;
            }
          }
        }
      }

      const DEFAULT_STRIDE = getAttributeStride(vfmtPosUvColor) >> 2;
      class BaseRenderData {
        get vertexCount() {
          return this._vc;
        }
        get indexCount() {
          return this._ic;
        }
        get stride() {
          return this._floatStride << 2;
        }
        get floatStride() {
          return this._floatStride;
        }
        get vertexFormat() {
          return this._vertexFormat;
        }
        get drawInfoType() {
          return this._drawInfoType;
        }
        set drawInfoType(type) {
          this._drawInfoType = type;
          if (this._renderDrawInfo) {
            this._renderDrawInfo.setDrawInfoType(type);
          }
        }
        get renderDrawInfo() {
          return this._renderDrawInfo;
        }
        get material() {
          return this._material;
        }
        set material(val) {
          this._material = val;
          if (this._renderDrawInfo) {
            this._renderDrawInfo.setMaterial(val);
          }
        }
        get dataHash() {
          return this._dataHash;
        }
        set dataHash(val) {
          this._dataHash = val;
          if (this._renderDrawInfo) {
            this._renderDrawInfo.setDataHash(val);
          }
        }
        get multiOwner() {
          return this._multiOwner;
        }
        set multiOwner(val) {
          this._multiOwner = val;
        }
        get batcher() {
          if (!this._batcher) {
            this._batcher = director.root.batcher2D;
          }
          return this._batcher;
        }
        constructor(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 = 0;
          this._multiOwner = false;
          this._batcher = null;
          this._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          this._vertexFormat = vertexFormat;
        }
        isValid() {
          return this._ic > 0 && this.chunk.vertexAccessor;
        }
        initRenderDrawInfo(comp, drawInfoType = 0) {
          {
            const renderEntity = comp.renderEntity;
            if (renderEntity.renderEntityType === 0) {
              if (!this._renderDrawInfo) {
                const drawInfo = renderEntity.getStaticRenderDrawInfo();
                if (drawInfo) {
                  this._renderDrawInfo = drawInfo;
                }
              }
            } else if (this.multiOwner === false) {
              if (!this._renderDrawInfo) {
                this._renderDrawInfo = new RenderDrawInfo();
                renderEntity.addDynamicRenderDrawInfo(this._renderDrawInfo);
              }
            }
            this.drawInfoType = drawInfoType;
            this.setRenderDrawInfoAttributes();
          }
        }
        removeRenderDrawInfo(comp) {
          {
            const renderEntity = comp.renderEntity;
            if (renderEntity.renderEntityType === 1) {
              renderEntity.removeDynamicRenderDrawInfo();
            } else if (renderEntity.renderEntityType === 0) {
              renderEntity.clearStaticRenderDrawInfos();
            }
          }
        }
        setRenderDrawInfoAttributes() {
          {
            if (!this._renderDrawInfo) {
              return;
            }
            if (this.chunk) {
              this._renderDrawInfo.setBufferId(this.chunk.bufferId);
              this._renderDrawInfo.setVertexOffset(this.chunk.vertexOffset);
              this._renderDrawInfo.setVB(this.chunk.vb);
              this._renderDrawInfo.setIB(this.chunk.ib);
              if (this.chunk.meshBuffer) {
                this._renderDrawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset);
                this._renderDrawInfo.setVData(this.chunk.meshBuffer.vData.buffer);
                this._renderDrawInfo.setIData(this.chunk.meshBuffer.iData.buffer);
              }
            }
            this._renderDrawInfo.setVBCount(this._vc);
            this._renderDrawInfo.setIBCount(this._ic);
            this._renderDrawInfo.setDataHash(this.dataHash);
            this._renderDrawInfo.setIsMeshBuffer(this._isMeshBuffer);
            this._renderDrawInfo.setMaterial(this.material);
            this._renderDrawInfo.setDrawInfoType(this._drawInfoType);
          }
        }
      } exports("BaseRenderData", BaseRenderData);
      class RenderData extends BaseRenderData {
        static add(vertexFormat = vfmtPosUvColor, accessor = null) {
          const rd = new RenderData(vertexFormat, accessor);
          if (!accessor) {
            const batcher = director.root.batcher2D;
            accessor = batcher.switchBufferAccessor(rd._vertexFormat);
          }
          rd._accessor = accessor;
          return rd;
        }
        static remove(data) {
          data.clear();
          data._accessor = null;
        }
        get dataLength() {
          return this._data.length;
        }
        set dataLength(length) {
          const data = this._data;
          if (data.length !== length) {
            for (let 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();
        }
        get data() {
          return this._data;
        }
        get vertDirty() {
          return this._vertDirty;
        }
        set vertDirty(val) {
          this._vertDirty = val;
          if (this._renderDrawInfo && val) {
            this._renderDrawInfo.setVertDirty(val);
          }
        }
        get textureHash() {
          return this._textureHash;
        }
        set textureHash(val) {
          this._textureHash = val;
        }
        set frame(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);
            }
          }
        }
        get frame() {
          return this._frame;
        }
        get accessor() {
          return this._accessor;
        }
        constructor(vertexFormat = vfmtPosUvColor, accessor = null) {
          super(vertexFormat);
          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;
        }
        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();
          if (this.multiOwner === false && this._renderDrawInfo) {
            this._renderDrawInfo.setDrawInfoType(this._drawInfoType);
            this._renderDrawInfo.setBufferId(this.chunk.bufferId);
            this._renderDrawInfo.setVertexOffset(this.chunk.vertexOffset);
            this._renderDrawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset);
            this._renderDrawInfo.setVB(this.chunk.vb);
            this._renderDrawInfo.setIB(this.chunk.ib);
            this._renderDrawInfo.setVData(this.chunk.meshBuffer.vData.buffer);
            this._renderDrawInfo.setIData(this.chunk.meshBuffer.iData.buffer);
            this._renderDrawInfo.setVBCount(this._vc);
            this._renderDrawInfo.setIBCount(this._ic);
          }
        }
        setRenderDrawInfoAttributes() {
          {
            if (!this._renderDrawInfo) {
              return;
            }
            this._renderDrawInfo.setAccId(this._accessor.id);
            super.setRenderDrawInfoAttributes();
            this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null);
            this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null);
          }
        }
        fillDrawInfoAttributes(drawInfo) {
          {
            if (!drawInfo) {
              return;
            }
            drawInfo.setDrawInfoType(this._drawInfoType);
            drawInfo.setAccAndBuffer(this._accessor.id, this.chunk.bufferId);
            drawInfo.setVertexOffset(this.chunk.vertexOffset);
            drawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset);
            drawInfo.setVB(this.chunk.vb);
            drawInfo.setIB(this.chunk.ib);
            drawInfo.setVData(this.chunk.meshBuffer.vData.buffer);
            drawInfo.setIData(this.chunk.meshBuffer.iData.buffer);
            drawInfo.setVBCount(this._vc);
            drawInfo.setIBCount(this._ic);
            drawInfo.setDataHash(this.dataHash);
            drawInfo.setIsMeshBuffer(this._isMeshBuffer);
          }
        }
        syncRender2dBuffer() {
          if (this.multiOwner === false) {
            if (!this._renderDrawInfo) {
              return;
            }
            this.renderDrawInfo.setStride(this.floatStride);
            this.renderDrawInfo.setVBCount(this.dataLength);
            this.renderDrawInfo.initRender2dBuffer();
          }
        }
        resizeAndCopy(vertexCount, indexCount) {
          if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return;
          this._vc = vertexCount;
          this._ic = indexCount;
          const oldChunk = this.chunk;
          this.chunk = this._accessor.allocateChunk(vertexCount, indexCount);
          if (oldChunk) {
            this.chunk.vb.set(oldChunk.vb);
            this._accessor.recycleChunk(oldChunk);
          }
          this.updateHash();
        }
        getMeshBuffer() {
          if (this.chunk && this._accessor) {
            return this._accessor.getMeshBuffer(this.chunk.bufferId);
          } else {
            return null;
          }
        }
        updateNode(comp) {
          this.layer = comp.node.layer;
          this.nodeDirty = false;
          this.hashDirty = true;
        }
        updatePass(comp) {
          this.material = comp.getRenderMaterial(0);
          this.passDirty = false;
          this.hashDirty = true;
        }
        updateTexture(frame) {
          this.frame = frame;
          this.textureHash = frame.getHash();
          this.textureDirty = false;
          this.hashDirty = true;
        }
        updateHash() {
          const bid = this.chunk ? this.chunk.bufferId : -1;
          const hashString = `${bid}${this.layer} ${this.textureHash}`;
          this.dataHash = murmurhash2_32_gc(hashString, 666);
          this.hashDirty = false;
        }
        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) {
            const 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);
            }
          }
          if (this.multiOwner === false) {
            {
              if (this._renderDrawInfo && this._renderDrawInfo.render2dBuffer) {
                assert(this._renderDrawInfo.render2dBuffer.length === this._floatStride * this._data.length, 'Vertex count doesn\'t match.');
              }
            }
            this._renderDrawInfo.fillRender2dBuffer(this._data);
          }
        }
        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;
          if (this._renderDrawInfo) {
            this._renderDrawInfo.clear();
          }
        }
        static createStaticVBAccessor(attributes, vCount, iCount) {
          const device = director.root.device;
          const accessor = new StaticVBAccessor(device, attributes, vCount, iCount);
          return accessor;
        }
      } exports("RenderData", RenderData);
      class MeshRenderData extends BaseRenderData {
        static add(vertexFormat = vfmtPosUvColor) {
          const rd = new MeshRenderData();
          rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          rd._vertexFormat = vertexFormat;
          return rd;
        }
        static remove(data) {
          data.clear();
        }
        set formatByte(value) {}
        get formatByte() {
          return this.stride;
        }
        get floatStride() {
          return this._floatStride;
        }
        get vDataOffset() {
          return this._byteLength >>> 2;
        }
        constructor(vertexFormat = vfmtPosUvColor) {
          super(vertexFormat);
          this._isMeshBuffer = true;
          this.vertexStart = 0;
          this.vertexRange = 0;
          this.indexStart = 0;
          this.indexRange = 0;
          this.lastFilledIndex = 0;
          this.lastFilledVertex = 0;
          this.frame = null;
          this._byteLength = 0;
          this._vertexBuffers = [];
          this._indexBuffer = null;
          this._iaPool = null;
          this._iaInfo = null;
          this.vData = new Float32Array(256 * this.stride);
          this.iData = new Uint16Array(256 * 6);
        }
        request(vertexCount, indexCount) {
          const byteOffset = this._byteLength + vertexCount * this.stride;
          const 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;
        }
        reserve(vertexCount, indexCount) {
          const newVBytes = this._byteLength + vertexCount * this.stride;
          const newICount = this.indexCount + indexCount;
          if (vertexCount + this.vertexCount > 65535) {
            return false;
          }
          let byteLength = this.vData.byteLength;
          let indicesLength = this.iData.length;
          let vCount = this.vData.length;
          let 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;
        }
        resize(vertexCount, indexCount) {
          const 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);
        }
        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;
        }
        requestIA(device) {
          this._initIAInfo(device);
          const ia = this._iaPool.add();
          ia.firstIndex = this.indexStart;
          ia.indexCount = this.indexRange;
          return ia;
        }
        uploadBuffers() {
          if (this._byteLength === 0 || !this._vertexBuffers[0] || !this._indexBuffer) {
            return;
          }
          const indexCount = this._ic;
          const verticesData = new Float32Array(this.vData.buffer, 0, this._byteLength >> 2);
          const indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
          const vertexBuffer = this._vertexBuffers[0];
          if (this._byteLength > vertexBuffer.size) {
            vertexBuffer.resize(this._byteLength);
          }
          vertexBuffer.update(verticesData);
          const indexBytes = indexCount << 1;
          if (indexBytes > this._indexBuffer.size) {
            this._indexBuffer.resize(indexBytes);
          }
          this._indexBuffer.update(indicesData);
        }
        freeIAPool() {
          if (this._iaPool) {
            this._iaPool.reset();
          }
        }
        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();
        }
        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);
        }
        _initIAInfo(device) {
          if (!this._iaInfo) {
            const vbStride = this.stride;
            const vbs = this._vertexBuffers;
            if (!vbs.length) {
              vbs.push(device.createBuffer(new BufferInfo(8 | 2, 1, vbStride, vbStride)));
            }
            const ibStride = 2;
            if (!this._indexBuffer) {
              this._indexBuffer = device.createBuffer(new BufferInfo(4 | 2, 1, ibStride, ibStride));
            }
            this._iaInfo = new InputAssemblerInfo(this._vertexFormat, vbs, this._indexBuffer);
            this._iaPool = new RecyclePool(() => device.createInputAssembler(this._iaInfo), 1, ia => {
              ia.destroy();
            });
          }
        }
        _reallocBuffer(vCount, iCount) {
          const oldVData = this.vData;
          this.vData = new Float32Array(vCount);
          if (oldVData) {
            this.vData.set(oldVData, 0);
          }
          const oldIData = this.iData;
          this.iData = new Uint16Array(iCount);
          if (oldIData) {
            this.iData.set(oldIData, 0);
          }
        }
        setRenderDrawInfoAttributes() {
          {
            if (!this._renderDrawInfo) {
              return;
            }
            this._renderDrawInfo.setVData(this.vData.buffer);
            this._renderDrawInfo.setIData(this.iData.buffer);
            this._renderDrawInfo.setVBCount(this._vc);
            this._renderDrawInfo.setIBCount(this._ic);
            this._renderDrawInfo.setVertexOffset(this.vertexStart);
            this._renderDrawInfo.setIndexOffset(this.indexStart);
            this._renderDrawInfo.setIsMeshBuffer(this._isMeshBuffer);
            this._renderDrawInfo.setMaterial(this.material);
            if (this.frame) {
              this._renderDrawInfo.setTexture(this.frame.getGFXTexture());
              this._renderDrawInfo.setSampler(this.frame.getGFXSampler());
            }
          }
        }
        particleInitRenderDrawInfo(entity) {
          {
            if (entity.renderEntityType === 0) {
              if (!this._renderDrawInfo) {
                const drawInfo = entity.getStaticRenderDrawInfo();
                if (drawInfo) {
                  this._renderDrawInfo = drawInfo;
                }
              }
            }
          }
        }
      } exports("MeshRenderData", MeshRenderData);

      var _dec$28, _dec2$1x, _class$28, _class2$1P, _initializer$1I, _initializer2$1k, _class3$z;
      const _vec2a = new Vec2();
      const _vec2b = new Vec2();
      const _vec3a = new Vec3();
      const _mat4_temp$5 = new Mat4();
      const _matrix = new Mat4();
      const _worldMatrix$1 = new Mat4();
      const _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      const _rect = new Rect$1();
      let UITransform = (_dec$28 = ccclass$H('cc.UITransform'), _dec2$1x = executionOrder$1(110), _dec$28(_class$28 = _dec2$1x(_class$28 = disallowMultiple$1(_class$28 = (_class2$1P = (_class3$z = class UITransform extends Component {
        constructor() {
          super();
          this._priority = 0;
          this._contentSize = _initializer$1I && _initializer$1I();
          this._anchorPoint = _initializer2$1k && _initializer2$1k();
        }
        get contentSize() {
          return this._contentSize;
        }
        set contentSize(value) {
          if (this._contentSize.equals(value)) {
            return;
          }
          {
            this._contentSize.set(value);
            this.node.emit("size-changed");
          }
          this._markRenderDataDirty();
        }
        get width() {
          return this._contentSize.width;
        }
        set width(value) {
          if (this._contentSize.width === value) {
            return;
          }
          {
            this._contentSize.width = value;
            this.node.emit("size-changed");
          }
          this._markRenderDataDirty();
        }
        get height() {
          return this._contentSize.height;
        }
        set height(value) {
          if (this.contentSize.height === value) {
            return;
          }
          {
            this._contentSize.height = value;
            this.node.emit("size-changed");
          }
          this._markRenderDataDirty();
        }
        get anchorPoint() {
          return this._anchorPoint;
        }
        set anchorPoint(value) {
          if (this._anchorPoint.equals(value)) {
            return;
          }
          this._anchorPoint.set(value);
          this.node.emit("anchor-changed", this._anchorPoint);
          this._markRenderDataDirty();
        }
        get anchorX() {
          return this._anchorPoint.x;
        }
        set anchorX(value) {
          if (this._anchorPoint.x === value) {
            return;
          }
          this._anchorPoint.x = value;
          this.node.emit("anchor-changed", this._anchorPoint);
          this._markRenderDataDirty();
        }
        get anchorY() {
          return this._anchorPoint.y;
        }
        set anchorY(value) {
          if (this._anchorPoint.y === value) {
            return;
          }
          this._anchorPoint.y = value;
          this.node.emit("anchor-changed", this._anchorPoint);
          this._markRenderDataDirty();
        }
        get priority() {
          return this._priority;
        }
        set priority(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);
          }
        }
        get visibility() {
          const camera = director.root.batcher2D.getFirstRenderCamera(this.node);
          return camera ? camera.visibility : 0;
        }
        get cameraPriority() {
          const camera = director.root.batcher2D.getFirstRenderCamera(this.node);
          return camera ? camera.priority : 0;
        }
        __preload() {
          this.node._uiProps.uiTransformComp = this;
        }
        onLoad() {
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        }
        onEnable() {
          this.node.on("parent-changed", this._parentChanged, this);
          this._markRenderDataDirty();
        }
        onDisable() {
          this.node.off("parent-changed", this._parentChanged, this);
        }
        onDestroy() {
          this.node._uiProps.uiTransformComp = null;
        }
        setContentSize(size, height) {
          const locContentSize = this._contentSize;
          let locWidth;
          let locHeight;
          if (height === undefined) {
            size = size;
            if (approx(size.width, locContentSize.width, EPSILON$2) && approx(size.height, locContentSize.height, EPSILON$2)) {
              return;
            }
            locWidth = size.width;
            locHeight = size.height;
          } else {
            size = size;
            if (approx(size, locContentSize.width, EPSILON$2) && approx(height, locContentSize.height, EPSILON$2)) {
              return;
            }
            locWidth = size;
            locHeight = height;
          }
          {
            locContentSize.width = locWidth;
            locContentSize.height = locHeight;
            this.node.emit("size-changed");
          }
          this._markRenderDataDirty();
        }
        setAnchorPoint(point, y) {
          const 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("anchor-changed", this._anchorPoint);
          this._markRenderDataDirty();
        }
        isHit(uiPoint) {
          const w = this._contentSize.width;
          const h = this._contentSize.height;
          const v2WorldPt = _vec2a;
          const testPt = _vec2b;
          const cameras = this._getRenderScene().cameras;
          for (let i = 0; i < cameras.length; i++) {
            const camera = cameras[i];
            if (!(camera.visibility & this.node.layer)) continue;
            camera.node.getWorldRT(_mat4_temp$5);
            const m12 = _mat4_temp$5.m12;
            const m13 = _mat4_temp$5.m13;
            const center = visibleRect.center;
            _mat4_temp$5.m12 = center.x - (_mat4_temp$5.m00 * m12 + _mat4_temp$5.m04 * m13);
            _mat4_temp$5.m13 = center.y - (_mat4_temp$5.m01 * m12 + _mat4_temp$5.m05 * m13);
            Mat4.invert(_mat4_temp$5, _mat4_temp$5);
            Vec2.transformMat4(v2WorldPt, uiPoint, _mat4_temp$5);
            this.node.getWorldMatrix(_worldMatrix$1);
            Mat4.invert(_mat4_temp$5, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$5, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$5);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            let 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;
        }
        hitTest(screenPoint, windowId = 0) {
          const w = this._contentSize.width;
          const h = this._contentSize.height;
          const v3WorldPt = _vec3a;
          const v2WorldPt = _vec2a;
          const testPt = _vec2b;
          const cameras = this._getRenderScene().cameras;
          for (let i = 0; i < cameras.length; i++) {
            const 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$5, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$5, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$5);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            let 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;
        }
        _maskTest(pointInWorldSpace) {
          var _this$node, _this$node$eventProce;
          const 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) {
            let parent = this.node;
            const length = maskList.length;
            for (let i = 0, j = 0; parent && j < length; ++i, parent = parent.parent) {
              const temp = maskList[j];
              if (i === temp.index) {
                if (parent === temp.comp.node) {
                  const 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;
        }
        convertToNodeSpaceAR(worldPoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          Mat4.invert(_mat4_temp$5, _worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, worldPoint, _mat4_temp$5);
        }
        convertToWorldSpaceAR(nodePoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, nodePoint, _worldMatrix$1);
        }
        getBoundingBox() {
          const rect = new Rect$1();
          this._selfBoundingBox(rect);
          Mat4.fromSRT(_matrix, this.node.rotation, this.node.position, this.node.scale);
          rect.transformMat4(_matrix);
          return rect;
        }
        getBoundingBoxToWorld() {
          const rect = new Rect$1();
          const locChildren = this.node.children;
          for (let i = 0; i < locChildren.length; ++i) {
            const child = locChildren[i];
            if (child && child.active) {
              const 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;
        }
        getBoundingBoxTo(targetMat) {
          const rect = new Rect$1();
          const locChildren = this.node.children;
          Mat4.invert(_mat4_temp$5, targetMat);
          for (let i = 0; i < locChildren.length; ++i) {
            const child = locChildren[i];
            if (child && child.active) {
              const uiTransform = child.getComponent(UITransform);
              if (uiTransform && uiTransform.contentSize.width && uiTransform.contentSize.height) {
                uiTransform._selfBoundingBox(_rect);
                Mat4.multiply(_matrix, child.worldMatrix, _mat4_temp$5);
                _rect.transformMat4(_matrix);
                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, this.node.worldMatrix, _mat4_temp$5);
            _rect.transformMat4(_matrix);
            if (rect.width === 0) {
              rect.set(_rect);
            } else {
              Rect$1.union(rect, rect, _rect);
            }
          }
          return rect;
        }
        getComputeAABB(out) {
          const width = this._contentSize.width;
          const height = this._contentSize.height;
          _rect.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          _rect.transformMat4(this.node.worldMatrix);
          const px = _rect.x + _rect.width * 0.5;
          const py = _rect.y + _rect.height * 0.5;
          const pz = this.node.worldPosition.z;
          const w = _rect.width / 2;
          const h = _rect.height / 2;
          const 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);
          }
        }
        _selfBoundingBox(out) {
          const width = this._contentSize.width;
          const height = this._contentSize.height;
          out.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          return out;
        }
        _parentChanged(node) {
          if (this.node.getComponent('cc.RenderRoot2D')) {
            return;
          }
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        }
        _markRenderDataDirty() {
          const uiComp = this.node._uiProps.uiComp;
          if (uiComp) {
            uiComp.markForUpdateRenderData();
          }
        }
        static insertChangeMap(node) {
          const key = node.uuid;
          if (!UITransform.priorityChangeNodeMap.has(key)) {
            UITransform.priorityChangeNodeMap.set(key, node);
          }
        }
        static _sortChildrenSibling(node) {
          const siblings = node.children;
          if (siblings) {
            siblings.sort((a, b) => {
              const aComp = a._uiProps.uiTransformComp;
              const bComp = b._uiProps.uiTransformComp;
              const ca = aComp ? aComp._priority : 0;
              const cb = bComp ? bComp._priority : 0;
              const diff = ca - cb;
              if (diff === 0) return a.getSiblingIndex() - b.getSiblingIndex();
              return diff;
            });
          }
        }
        static _sortSiblings() {
          UITransform.priorityChangeNodeMap.forEach((node, ID) => {
            UITransform._sortChildrenSibling(node);
            node._updateSiblingIndex();
            node.emit('childrenSiblingOrderChanged');
          });
          UITransform.priorityChangeNodeMap.clear();
        }
        static _cleanChangeMap() {
          UITransform.priorityChangeNodeMap.clear();
        }
      }, _class3$z.EventType = NodeEventType, _class3$z.priorityChangeNodeMap = new Map(), _class3$z), (_initializer$1I = applyDecoratedInitializer(_class2$1P.prototype, "_contentSize", [serializable$l], function () {
        return new Size$1(100, 100);
      }), _initializer2$1k = applyDecoratedInitializer(_class2$1P.prototype, "_anchorPoint", [serializable$l], function () {
        return new Vec2(0.5, 0.5);
      })), _class2$1P)) || _class$28) || _class$28) || _class$28); exports({ UITransform: UITransform, UITransformComponent: UITransform });
      director.on("director_after_update", UITransform._sortSiblings);
      director.on("director_before_scene_launch", UITransform._cleanChangeMap);

      const MaterialInstance = jsb.MaterialInstance;
      const materialInstanceProto = jsb.MaterialInstance.prototype;
      Object.defineProperty(materialInstanceProto, 'parent', {
        configurable: true,
        enumerable: true,
        get() {
          return this._parent;
        }
      });
      Object.defineProperty(materialInstanceProto, 'owner', {
        configurable: true,
        enumerable: true,
        get() {
          return this._owner;
        }
      });
      materialInstanceProto._ctor = function (info) {
        jsb.Material.prototype._ctor.apply(this, arguments);
        this._registerListeners();
        this._parent = info.parent;
        this._owner = info.owner || null;
        this._subModelIdx = info.subModelIdx || 0;
        this._passes = this.getPasses();
      };
      materialInstanceProto._onRebuildPSO = function () {
        if (this._owner) {
          this._owner._onRebuildPSO(this._subModelIdx, this);
        }
      };

      var _dec$27, _dec2$1w, _dec3$15, _class$27, _class2$1O, _initializer$1H;
      const _matInsInfo = {
        parent: null,
        owner: null,
        subModelIdx: 0
      };
      const {
        ccclass: ccclass$G,
        serializable: serializable$k,
        disallowMultiple,
        type: type$9,
        displayOrder: displayOrder$1,
        displayName: displayName$1
      } = _decorator;
      let Renderer = exports("Renderer", (_dec$27 = ccclass$G('cc.Renderer'), _dec2$1w = type$9(Material$1), _dec3$15 = type$9([Material$1]), _dec$27(_class$27 = disallowMultiple(_class$27 = (_class2$1O = class Renderer extends Component {
        constructor() {
          super();
          this._materials = _initializer$1H && _initializer$1H();
          this._materialInstances = [];
        }
        get sharedMaterial() {
          return this.getSharedMaterial(0);
        }
        get sharedMaterials() {
          return this._materials;
        }
        set sharedMaterials(val) {
          for (let i = 0; i < val.length; i++) {
            if (val[i] !== this._materials[i]) {
              this.setSharedMaterial(val[i], i);
            }
          }
          if (val.length < this._materials.length) {
            for (let i = val.length; i < this._materials.length; i++) {
              this.setSharedMaterial(null, i);
            }
            this._materials.splice(val.length);
          }
        }
        get material() {
          return this.getMaterialInstance(0);
        }
        set material(val) {
          if (this._materials.length === 1 && !this._materialInstances[0] && this._materials[0] === val) {
            return;
          }
          this.setMaterialInstance(val, 0);
        }
        get materials() {
          for (let i = 0; i < this._materials.length; i++) {
            this._materialInstances[i] = this.getMaterialInstance(i);
          }
          return this._materialInstances;
        }
        set materials(val) {
          const newLength = val.length;
          const oldLength = this._materials.length;
          for (let i = newLength; i < oldLength; i++) {
            this.setMaterialInstance(null, i);
          }
          this._materials.length = newLength;
          this._materialInstances.length = newLength;
          for (let i = 0; i < newLength; i++) {
            if (this._materialInstances[i] != val[i]) {
              this.setMaterialInstance(val[i], i);
            }
          }
        }
        getMaterial(idx) {
          return this.getSharedMaterial(idx);
        }
        setMaterial(material, index) {
          this.setSharedMaterial(material, index);
        }
        getSharedMaterial(idx) {
          if (idx < 0 || idx >= this._materials.length) {
            return null;
          }
          return this._materials[idx];
        }
        setSharedMaterial(material, index) {
          if (material && material instanceof MaterialInstance) {
            errorID(12012);
          }
          this._materials[index] = material;
          const inst = this._materialInstances[index];
          if (inst) {
            inst.destroy();
            this._materialInstances[index] = null;
          }
          this._onMaterialModified(index, this._materials[index]);
        }
        getMaterialInstance(idx) {
          const mat = this._materials[idx];
          if (!mat) {
            return null;
          }
          if (!this._materialInstances[idx]) {
            _matInsInfo.parent = this._materials[idx];
            _matInsInfo.owner = this;
            _matInsInfo.subModelIdx = idx;
            const instantiated = new MaterialInstance(_matInsInfo);
            _matInsInfo.parent = null;
            _matInsInfo.owner = null;
            _matInsInfo.subModelIdx = 0;
            this.setMaterialInstance(instantiated, idx);
          }
          return this._materialInstances[idx];
        }
        setMaterialInstance(matInst, index) {
          if (typeof matInst === 'number') {
            warnID(12007);
            const temp = matInst;
            matInst = index;
            index = temp;
          }
          const 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);
          }
        }
        getRenderMaterial(index) {
          return this._materialInstances[index] || this._materials[index];
        }
        _onMaterialModified(index, material) {}
        _onRebuildPSO(index, material) {}
        _clearMaterials() {}
      }, (_applyDecoratedDescriptor(_class2$1O.prototype, "sharedMaterials", [_dec2$1w], Object.getOwnPropertyDescriptor(_class2$1O.prototype, "sharedMaterials"), _class2$1O.prototype), _initializer$1H = applyDecoratedInitializer(_class2$1O.prototype, "_materials", [_dec3$15], function () {
        return [];
      })), _class2$1O)) || _class$27) || _class$27));

      class RenderEntity {
        get nativeObj() {
          return this._nativeObj;
        }
        get renderDrawInfoArr() {
          return this._dynamicDrawInfoArr;
        }
        get renderEntityType() {
          return this._renderEntityType;
        }
        get color() {
          return this._color;
        }
        set color(val) {
          this._color = val;
          {
            this._uint8SharedBuffer[0] = val.r;
            this._uint8SharedBuffer[1] = val.g;
            this._uint8SharedBuffer[2] = val.b;
            this._uint8SharedBuffer[3] = val.a;
          }
        }
        get localOpacity() {
          return this._localOpacity;
        }
        set localOpacity(val) {
          this._localOpacity = val;
          {
            this._floatSharedBuffer[0] = val;
          }
        }
        get colorDirty() {
          {
            this._colorDirty = !!this._boolSharedBuffer[0];
          }
          return this._colorDirty;
        }
        set colorDirty(val) {
          this._colorDirty = val;
          {
            this._boolSharedBuffer[0] = val ? 1 : 0;
          }
        }
        get enabled() {
          return this._enabled;
        }
        set enabled(val) {
          this._enabled = val;
          {
            this._boolSharedBuffer[1] = val ? 1 : 0;
          }
        }
        constructor(entityType) {
          this._renderEntityType = 0;
          this._dynamicDrawInfoArr = [];
          this._node = null;
          this._renderTransform = null;
          this._stencilStage = 0;
          this._useLocal = false;
          this._maskMode = 0;
          this._color = Color$1.WHITE.clone();
          this._localOpacity = 255;
          this._colorDirty = true;
          this._enabled = false;
          {
            if (!this._nativeObj) {
              this._nativeObj = new NativeRenderEntity(entityType);
            }
            this._renderEntityType = entityType;
            this.initSharedBuffer();
          }
        }
        addDynamicRenderDrawInfo(renderDrawInfo) {
          {
            if (renderDrawInfo) {
              this._dynamicDrawInfoArr.push(renderDrawInfo);
              this._nativeObj.addDynamicRenderDrawInfo(renderDrawInfo.nativeObj);
            }
          }
        }
        removeDynamicRenderDrawInfo() {
          {
            this._dynamicDrawInfoArr.pop();
            this._nativeObj.removeDynamicRenderDrawInfo();
          }
        }
        clearDynamicRenderDrawInfos() {
          {
            this._dynamicDrawInfoArr.length = 0;
            this._nativeObj.clearDynamicRenderDrawInfos();
          }
        }
        clearStaticRenderDrawInfos() {
          {
            this._nativeObj.clearStaticRenderDrawInfos();
          }
        }
        setDynamicRenderDrawInfo(renderDrawInfo, index) {
          {
            if (renderDrawInfo) {
              if (this._dynamicDrawInfoArr.length < index + 1) {
                this._dynamicDrawInfoArr.push(renderDrawInfo);
                this._nativeObj.addDynamicRenderDrawInfo(renderDrawInfo.nativeObj);
              } else {
                this._dynamicDrawInfoArr[index] = renderDrawInfo;
                this._nativeObj.setDynamicRenderDrawInfo(renderDrawInfo.nativeObj, index);
              }
            }
          }
        }
        setMaskMode(mode) {
          {
            this._uint8SharedBuffer[4] = mode;
          }
          this._maskMode = mode;
        }
        getStaticRenderDrawInfo() {
          {
            const nativeDrawInfo = this._nativeObj.getStaticRenderDrawInfo(this._nativeObj.staticDrawInfoSize++);
            const drawInfo = new RenderDrawInfo(nativeDrawInfo);
            return drawInfo;
          }
        }
        setNode(node) {
          {
            if (this._node !== node) {
              this._nativeObj.node = node;
            }
          }
          this._node = node;
        }
        setRenderTransform(renderTransform) {
          {
            if (this._renderTransform !== renderTransform) {
              this._nativeObj.renderTransform = renderTransform;
            }
          }
          this._renderTransform = renderTransform;
        }
        setStencilStage(stage) {
          {
            if (this._stencilStage !== stage) {
              this._nativeObj.stencilStage = stage;
            }
          }
          this._stencilStage = stage;
        }
        setUseLocal(useLocal) {
          {
            this._boolSharedBuffer[2] = useLocal ? 1 : 0;
          }
          this._useLocal = useLocal;
        }
        initSharedBuffer() {
          {
            const buffer = this._nativeObj.getEntitySharedBufferForJS();
            let offset = 0;
            this._floatSharedBuffer = new Float32Array(buffer, offset, 1);
            offset += 1 * 4;
            this._uint8SharedBuffer = new Uint8Array(buffer, offset, 5);
            offset += 5 * 1;
            this._boolSharedBuffer = new Uint8Array(buffer, offset, 3);
          }
        }
      }

      var _dec$26, _dec2$1v, _dec3$14, _dec4$J, _class$26, _class2$1N, _initializer$1G, _initializer2$1j, _initializer3$Y, _initializer4$R, _initializer5$E, _class3$y;
      ccenum(BlendFactor);
      ccenum(BlendOp);
      ccenum(ColorMask);
      const InstanceMaterialType = exports("InstanceMaterialType", {
        "ADD_COLOR": 0,
        "ADD_COLOR_AND_TEXTURE": 1,
        "GRAYSCALE": 2,
        "USE_ALPHA_SEPARATED": 3,
        "USE_ALPHA_SEPARATED_AND_GRAY": 4
      });
      let UIRenderer = (_dec$26 = ccclass$H('cc.UIRenderer'), _dec2$1v = requireComponent(UITransform), _dec3$14 = type$a(Material$1), _dec4$J = type$a(Material$1), _dec$26(_class$26 = _dec2$1v(_class$26 = (_class2$1N = (_class3$y = class UIRenderer extends Renderer {
        constructor() {
          super();
          this._renderData = null;
          this._materials = _initializer$1G && _initializer$1G();
          this._customMaterial = _initializer2$1j && _initializer2$1j();
          this._srcBlendFactor = _initializer3$Y && _initializer3$Y();
          this._dstBlendFactor = _initializer4$R && _initializer4$R();
          this._color = _initializer5$E && _initializer5$E();
          this._stencilStage = 0;
          this._assembler = null;
          this._postAssembler = null;
          this._renderDataFlag = true;
          this._renderFlag = true;
          this._instanceMaterialType = -1;
          this._srcBlendFactorCache = 2;
          this._dstBlendFactorCache = 4;
          this._dirtyVersion = -1;
          this._internalId = -1;
          this._flagChangedVersion = -1;
          this._useVertexOpacity = false;
          this._lastParent = null;
          this._renderEntity = this.createRenderEntity();
        }
        get sharedMaterials() {
          return this._materials;
        }
        set sharedMaterials(val) {
          for (let i = 0; i < val.length; i++) {
            if (val[i] !== this._materials[i]) {
              this.setSharedMaterial(val[i], i);
            }
          }
          if (val.length < this._materials.length) {
            for (let i = val.length; i < this._materials.length; i++) {
              this.setSharedMaterial(null, i);
            }
            this._materials.splice(val.length);
          }
        }
        get customMaterial() {
          return this._customMaterial;
        }
        set customMaterial(val) {
          this._customMaterial = val;
          this.updateMaterial();
        }
        get color() {
          return this._color;
        }
        set color(value) {
          if (this._color.equals(value)) {
            return;
          }
          this._color.set(value);
          this._updateColor();
        }
        get renderData() {
          return this._renderData;
        }
        setRenderData(renderData) {
          this._renderData = renderData;
        }
        get useVertexOpacity() {
          return this._useVertexOpacity;
        }
        get stencilStage() {
          return this._stencilStage;
        }
        set stencilStage(val) {
          this._stencilStage = val;
          this._renderEntity.setStencilStage(val);
        }
        get srcBlendFactor() {
          return this._srcBlendFactor;
        }
        set srcBlendFactor(srcBlendFactor) {
          this._srcBlendFactor = srcBlendFactor;
        }
        get batcher() {
          return director.root.batcher2D;
        }
        get renderEntity() {
          {
            assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
          }
          return this._renderEntity;
        }
        onLoad() {
          this._renderEntity.setNode(this.node);
        }
        __preload() {
          this.node._uiProps.uiComp = this;
          if (this._flushAssembler) {
            this._flushAssembler();
          }
        }
        onEnable() {
          this.node.on("anchor-changed", this._nodeStateChange, this);
          this.node.on("size-changed", this._nodeStateChange, this);
          this.node.on("parent-changed", this._colorDirty, this);
          this.updateMaterial();
          this._colorDirty();
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        }
        onRestore() {
          this.updateMaterial();
          this.markForUpdateRenderData();
        }
        onDisable() {
          this.node.off("anchor-changed", this._nodeStateChange, this);
          this.node.off("size-changed", this._nodeStateChange, this);
          this.node.off("parent-changed", this._colorDirty, this);
          uiRendererManager.removeRenderer(this);
          this._renderFlag = false;
          this._renderEntity.enabled = false;
        }
        onDestroy() {
          this._renderEntity.setNode(null);
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
          this.destroyRenderData();
          if (this._materialInstances) {
            for (let i = 0; i < this._materialInstances.length; i++) {
              const instance = this._materialInstances[i];
              if (instance) {
                instance.destroy();
              }
            }
          }
        }
        markForUpdateRenderData(enable = true) {
          if (enable) {
            const renderData = this._renderData;
            if (renderData) {
              renderData.vertDirty = true;
            }
            uiRendererManager.markDirtyRenderer(this);
          }
        }
        requestRenderData(drawInfoType = 0) {
          const data = RenderData.add();
          data.initRenderDrawInfo(this, drawInfoType);
          this._renderData = data;
          return data;
        }
        destroyRenderData() {
          if (!this._renderData) {
            return;
          }
          this._renderData.removeRenderDrawInfo(this);
          RenderData.remove(this._renderData);
          this._renderData = null;
        }
        updateRenderer() {
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
          this._renderFlag = this._canRender();
          this._renderEntity.enabled = this._renderFlag;
        }
        fillBuffers(render) {
          if (this._renderFlag) {
            this._render(render);
          }
        }
        postUpdateAssembler(render) {
          if (this._postAssembler && this._renderFlag) {
            this._postRender(render);
          }
        }
        _render(render) {}
        _postRender(render) {}
        _canRender() {
          {
            assert(this.isValid, 'this component should not be invalid!');
          }
          return this.getSharedMaterial(0) !== null && this._enabled && this._color.a > 0;
        }
        _postCanRender() {}
        updateMaterial() {
          if (this._customMaterial) {
            if (this.getSharedMaterial(0) !== this._customMaterial) {
              this.setSharedMaterial(this._customMaterial, 0);
            }
            return;
          }
          const mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          if (this.stencilStage === 2 || this.stencilStage === 6) {
            this.getMaterialInstance(0).recompileShaders({
              USE_ALPHA_TEST: true
            });
          }
          this._updateBlendFunc();
        }
        _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);
            const renderFlag = this._renderFlag;
            this._renderFlag = this._canRender();
            this.setEntityEnabled(this._renderFlag);
            if (renderFlag !== this._renderFlag) {
              const renderData = this.renderData;
              if (renderData) {
                renderData.vertDirty = true;
              }
            }
          }
        }
        static setEntityColorDirtyRecursively(node, dirty) {
          const render = node._uiProps.uiComp;
          if (render && render.color) {
            render._renderEntity.colorDirty = dirty;
          }
          for (let i = 0; i < node.children.length; i++) {
            UIRenderer.setEntityColorDirtyRecursively(node.children[i], dirty);
          }
        }
        setEntityColorDirty(dirty) {
          {
            UIRenderer.setEntityColorDirtyRecursively(this.node, dirty);
          }
        }
        setEntityColor(color) {
          {
            this._renderEntity.color = color;
          }
        }
        setEntityOpacity(opacity) {
          {
            this._renderEntity.localOpacity = opacity;
          }
        }
        setEntityEnabled(enabled) {
          {
            this._renderEntity.enabled = enabled;
          }
        }
        _updateBlendFunc() {
          let 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 = 4;
            target.blendDst = this._dstBlendFactor;
            target.blendSrc = this._srcBlendFactor;
            const targetPass = this.getMaterialInstance(0).passes[0];
            targetPass.blendState.setTarget(0, target);
            targetPass._updatePassHash();
            this._dstBlendFactorCache = this._dstBlendFactor;
            this._srcBlendFactorCache = this._srcBlendFactor;
          }
        }
        _nodeStateChange(transformType) {
          if (this._renderData) {
            this.markForUpdateRenderData();
          }
          for (let i = 0; i < this.node.children.length; ++i) {
            const child = this.node.children[i];
            const renderComp = child.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.markForUpdateRenderData();
            }
          }
        }
        _colorDirty() {
          this.node._uiProps.colorDirty = true;
          this.setEntityColorDirty(true);
        }
        _onMaterialModified(idx, material) {
          if (this._renderData) {
            this.markForUpdateRenderData();
            this._renderData.passDirty = true;
          }
          super._onMaterialModified(idx, material);
        }
        _updateBuiltinMaterial() {
          let mat;
          switch (this._instanceMaterialType) {
            case 0:
              mat = builtinResMgr.get(`ui-base-material`);
              break;
            case 2:
              mat = builtinResMgr.get(`ui-sprite-gray-material`);
              break;
            case 3:
              mat = builtinResMgr.get(`ui-sprite-alpha-sep-material`);
              break;
            case 4:
              mat = builtinResMgr.get(`ui-sprite-gray-alpha-sep-material`);
              break;
            default:
              mat = builtinResMgr.get(`ui-sprite-material`);
              break;
          }
          return mat;
        }
        setNodeDirty() {
          if (this._renderData) {
            this._renderData.nodeDirty = true;
          }
        }
        setTextureDirty() {
          if (this._renderData) {
            this._renderData.textureDirty = true;
          }
        }
        createRenderEntity() {
          return new RenderEntity(0);
        }
      }, _class3$y.BlendState = BlendFactor, _class3$y.Assembler = null, _class3$y.PostAssembler = null, _class3$y), (_applyDecoratedDescriptor(_class2$1N.prototype, "sharedMaterials", [override$1], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "sharedMaterials"), _class2$1N.prototype), _applyDecoratedDescriptor(_class2$1N.prototype, "customMaterial", [_dec3$14], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "customMaterial"), _class2$1N.prototype), _initializer$1G = applyDecoratedInitializer(_class2$1N.prototype, "_materials", [override$1], function () {
        return [];
      }), _initializer2$1j = applyDecoratedInitializer(_class2$1N.prototype, "_customMaterial", [_dec4$J], function () {
        return null;
      }), _initializer3$Y = applyDecoratedInitializer(_class2$1N.prototype, "_srcBlendFactor", [serializable$l], function () {
        return 2;
      }), _initializer4$R = applyDecoratedInitializer(_class2$1N.prototype, "_dstBlendFactor", [serializable$l], function () {
        return 4;
      }), _initializer5$E = applyDecoratedInitializer(_class2$1N.prototype, "_color", [serializable$l], function () {
        return Color$1.WHITE.clone();
      })), _class2$1N)) || _class$26) || _class$26); exports({ UIRenderer: UIRenderer, RenderComponent: UIRenderer, UIRenderable: UIRenderer, Renderable2D: UIRenderer });
      cclegacy.internal.UIRenderer = UIRenderer;

      class TextStyle {
        constructor() {
          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;
        }
        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;
        }
      }

      class TextLayout {
        constructor() {
          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 = [];
        }
        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;
        }
      }

      class TextOutputLayoutData {
        constructor() {
          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();
        }
        reset() {
          this.parsedString.length = 0;
          this.nodeContentSize.set(0, 0);
          this.canvasSize.set();
          this.canvasPadding.set();
          this.contentSizeExtend.set();
          this.startPosition.set();
        }
      }
      class TextOutputRenderData {
        constructor() {
          this.quadCount = 0;
          this.vertexBuffer = [];
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        }
        reset() {
          this.quadCount = 0;
          this.vertexBuffer.length = 0;
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        }
      }

      var _dec$25, _dec2$1u, _dec3$13, _dec4$I, _dec5$D, _dec6$u, _dec7$n, _class$25, _class2$1M, _initializer$1F, _initializer2$1i, _initializer3$X, _initializer4$Q, _initializer5$D, _initializer6$w, _initializer7$n, _initializer8$l, _initializer9$j, _initializer10$i, _initializer11$h, _initializer12$g, _initializer13$d, _initializer14$b, _initializer15$8, _initializer16$8, _initializer17$5, _initializer18$5, _initializer19$4, _initializer20$4, _initializer21$4, _initializer22$3, _initializer23$2, _initializer24$2, _class3$x;
      const tempColor$2 = Color$1.WHITE.clone();
      const HorizontalTextAlignment = exports("HorizontalTextAlignment", {
        "LEFT": 0,
        "CENTER": 1,
        "RIGHT": 2
      });
      ccenum(HorizontalTextAlignment);
      const VerticalTextAlignment = exports("VerticalTextAlignment", {
        "TOP": 0,
        "CENTER": 1,
        "BOTTOM": 2
      });
      ccenum(VerticalTextAlignment);
      const Overflow = exports("Overflow", {
        "NONE": 0,
        "CLAMP": 1,
        "SHRINK": 2,
        "RESIZE_HEIGHT": 3
      });
      ccenum(Overflow);
      const CacheMode = exports("CacheMode", {
        "NONE": 0,
        "BITMAP": 1,
        "CHAR": 2
      });
      ccenum(CacheMode);
      let Label = (_dec$25 = ccclass$H('cc.Label'), _dec2$1u = executionOrder$1(110), _dec3$13 = type$a(HorizontalTextAlignment), _dec4$I = type$a(VerticalTextAlignment), _dec5$D = type$a(Overflow), _dec6$u = type$a(Font), _dec7$n = type$a(CacheMode), _dec$25(_class$25 = _dec2$1u(_class$25 = (_class2$1M = (_class3$x = class Label extends UIRenderer {
        get string() {
          return this._string;
        }
        set string(value) {
          if (value === null || value === undefined) {
            value = '';
          } else {
            value = value.toString();
          }
          if (this._string === value) {
            return;
          }
          this._string = value;
          this.markForUpdateRenderData();
        }
        get horizontalAlign() {
          return this._horizontalAlign;
        }
        set horizontalAlign(value) {
          if (this._horizontalAlign === value) {
            return;
          }
          this._horizontalAlign = value;
          this.markForUpdateRenderData();
        }
        get verticalAlign() {
          return this._verticalAlign;
        }
        set verticalAlign(value) {
          if (this._verticalAlign === value) {
            return;
          }
          this._verticalAlign = value;
          this.markForUpdateRenderData();
        }
        get actualFontSize() {
          return this._actualFontSize;
        }
        set actualFontSize(value) {
          this._actualFontSize = value;
        }
        get fontSize() {
          return this._fontSize;
        }
        set fontSize(value) {
          if (this._fontSize === value) {
            return;
          }
          this._fontSize = value;
          this.markForUpdateRenderData();
        }
        get lineHeight() {
          return this._lineHeight;
        }
        set lineHeight(value) {
          if (this._lineHeight === value) {
            return;
          }
          this._lineHeight = value;
          this.markForUpdateRenderData();
        }
        get spacingX() {
          return this._spacingX;
        }
        set spacingX(value) {
          if (this._spacingX === value) {
            return;
          }
          this._spacingX = value;
          this.markForUpdateRenderData();
        }
        get overflow() {
          return this._overflow;
        }
        set overflow(value) {
          if (this._overflow === value) {
            return;
          }
          this._overflow = value;
          this.markForUpdateRenderData();
        }
        get enableWrapText() {
          return this._enableWrapText;
        }
        set enableWrapText(value) {
          if (this._enableWrapText === value) {
            return;
          }
          this._enableWrapText = value;
          this.markForUpdateRenderData();
        }
        get useSystemFont() {
          return this._isSystemFontUsed;
        }
        set useSystemFont(value) {
          if (this._isSystemFontUsed === value) {
            return;
          }
          this.destroyRenderData();
          this._isSystemFontUsed = !!value;
          if (value) {
            this.font = null;
          }
          this._flushAssembler();
          this.markForUpdateRenderData();
        }
        get fontFamily() {
          return this._fontFamily;
        }
        set fontFamily(value) {
          if (this._fontFamily === value) {
            return;
          }
          this._fontFamily = value;
          this.markForUpdateRenderData();
        }
        get font() {
          return this._font;
        }
        set font(value) {
          if (this._font === value) {
            return;
          }
          this._isSystemFontUsed = !value;
          this._font = value;
          this.destroyRenderData();
          this._fontAtlas = null;
          this.updateRenderData(true);
        }
        get cacheMode() {
          return this._cacheMode;
        }
        set cacheMode(value) {
          if (this._cacheMode === value) {
            return;
          }
          if (this._cacheMode === 1 && !(this._font instanceof BitmapFont) && this._ttfSpriteFrame) {
            this._ttfSpriteFrame._resetDynamicAtlasFrame();
          }
          if (this._cacheMode === 2) {
            this._ttfSpriteFrame = null;
          }
          this._cacheMode = value;
          this.updateRenderData(true);
        }
        get isBold() {
          return this._isBold;
        }
        set isBold(value) {
          if (this._isBold === value) {
            return;
          }
          this._isBold = value;
          this.markForUpdateRenderData();
        }
        get isItalic() {
          return this._isItalic;
        }
        set isItalic(value) {
          if (this._isItalic === value) {
            return;
          }
          this._isItalic = value;
          this.markForUpdateRenderData();
        }
        get isUnderline() {
          return this._isUnderline;
        }
        set isUnderline(value) {
          if (this._isUnderline === value) {
            return;
          }
          this._isUnderline = value;
          this.markForUpdateRenderData();
        }
        get underlineHeight() {
          return this._underlineHeight;
        }
        set underlineHeight(value) {
          if (this._underlineHeight === value) return;
          this._underlineHeight = value;
          this.markForUpdateRenderData();
        }
        get enableOutline() {
          return this._enableOutline;
        }
        set enableOutline(value) {
          if (this._enableOutline === value) return;
          this._enableOutline = value;
          this.markForUpdateRenderData();
        }
        get outlineColor() {
          return this._outlineColor;
        }
        set outlineColor(value) {
          if (this._outlineColor === value) return;
          this._outlineColor.set(value);
          this.markForUpdateRenderData();
        }
        get outlineWidth() {
          return this._outlineWidth;
        }
        set outlineWidth(value) {
          if (this._outlineWidth === value) return;
          this._outlineWidth = value;
          this.markForUpdateRenderData();
        }
        get enableShadow() {
          return this._enableShadow;
        }
        set enableShadow(value) {
          if (this._enableShadow === value) return;
          this._enableShadow = value;
          this.markForUpdateRenderData();
        }
        get shadowColor() {
          return this._shadowColor;
        }
        set shadowColor(value) {
          if (this._shadowColor === value) return;
          this._shadowColor.set(value);
          this.markForUpdateRenderData();
        }
        get shadowOffset() {
          return this._shadowOffset;
        }
        set shadowOffset(value) {
          if (this._shadowOffset === value) return;
          this._shadowOffset.set(value);
          this.markForUpdateRenderData();
        }
        get shadowBlur() {
          return this._shadowBlur;
        }
        set shadowBlur(value) {
          if (this._shadowBlur === value) return;
          this._shadowBlur = value;
          this.markForUpdateRenderData();
        }
        get spriteFrame() {
          return this._texture;
        }
        get ttfSpriteFrame() {
          return this._ttfSpriteFrame;
        }
        get assemblerData() {
          return this._assemblerData;
        }
        get fontAtlas() {
          return this._fontAtlas;
        }
        set fontAtlas(value) {
          this._fontAtlas = value;
        }
        get _bmFontOriginalSize() {
          if (this._font instanceof BitmapFont) {
            return this._font.fontSize;
          } else {
            return -1;
          }
        }
        get textStyle() {
          return this._textStyle;
        }
        get textLayout() {
          return this._textLayout;
        }
        get textRenderData() {
          return this._textRenderData;
        }
        get textLayoutData() {
          return this._textLayoutData;
        }
        get contentWidth() {
          return this._contentWidth;
        }
        set contentWidth(val) {
          this._contentWidth = val;
        }
        constructor() {
          super();
          this._string = _initializer$1F && _initializer$1F();
          this._horizontalAlign = _initializer2$1i && _initializer2$1i();
          this._verticalAlign = _initializer3$X && _initializer3$X();
          this._actualFontSize = _initializer4$Q && _initializer4$Q();
          this._fontSize = _initializer5$D && _initializer5$D();
          this._fontFamily = _initializer6$w && _initializer6$w();
          this._lineHeight = _initializer7$n && _initializer7$n();
          this._overflow = _initializer8$l && _initializer8$l();
          this._enableWrapText = _initializer9$j && _initializer9$j();
          this._font = _initializer10$i && _initializer10$i();
          this._isSystemFontUsed = _initializer11$h && _initializer11$h();
          this._spacingX = _initializer12$g && _initializer12$g();
          this._isItalic = _initializer13$d && _initializer13$d();
          this._isBold = _initializer14$b && _initializer14$b();
          this._isUnderline = _initializer15$8 && _initializer15$8();
          this._underlineHeight = _initializer16$8 && _initializer16$8();
          this._cacheMode = _initializer17$5 && _initializer17$5();
          this._enableOutline = _initializer18$5 && _initializer18$5();
          this._outlineColor = _initializer19$4 && _initializer19$4();
          this._outlineWidth = _initializer20$4 && _initializer20$4();
          this._enableShadow = _initializer21$4 && _initializer21$4();
          this._shadowColor = _initializer22$3 && _initializer22$3();
          this._shadowOffset = _initializer23$2 && _initializer23$2();
          this._shadowBlur = _initializer24$2 && _initializer24$2();
          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();
        }
        onEnable() {
          super.onEnable();
          if (!this._font && !this._isSystemFontUsed) {
            this.useSystemFont = true;
          }
          if (this._isSystemFontUsed && !this._fontFamily) {
            this.fontFamily = 'Arial';
          }
          this._applyFontTexture();
        }
        destroyTtfSpriteFrame() {
          if (!this._ttfSpriteFrame) {
            return;
          }
          this._ttfSpriteFrame._resetDynamicAtlasFrame();
          const tex = this._ttfSpriteFrame.texture;
          this._ttfSpriteFrame.destroy();
          if (tex) {
            const tex2d = tex;
            if (tex2d.image) {
              tex2d.image.destroy();
            }
            tex.destroy();
          }
          this._ttfSpriteFrame = null;
        }
        _onPreDestroy() {
          super._onPreDestroy();
          if (!this._isOnLoadCalled) {
            this.destroyTtfSpriteFrame();
          }
        }
        onDestroy() {
          if (this._assembler && this._assembler.resetAssemblerData) {
            this._assembler.resetAssemblerData(this._assemblerData);
          }
          this._assemblerData = null;
          this.destroyTtfSpriteFrame();
          this._letterTexture = null;
          super.onDestroy();
        }
        updateRenderData(force = false) {
          if (force) {
            this._flushAssembler();
            if (this.renderData) this.renderData.vertDirty = true;
            this._applyFontTexture();
          }
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
        }
        _render(render) {
          render.commitComp(this, this.renderData, this._texture, this._assembler, null);
        }
        _updateColor() {
          super._updateColor();
          this.markForUpdateRenderData();
        }
        setEntityColor(color) {
          {
            if (this._font instanceof BitmapFont) {
              this._renderEntity.color = color;
            } else {
              tempColor$2.set(255, 255, 255, color.a);
              this._renderEntity.color = tempColor$2;
            }
          }
        }
        _canRender() {
          if (!super._canRender() || !this._string) {
            return false;
          }
          const font = this._font;
          if (font && font instanceof BitmapFont) {
            const spriteFrame = font.spriteFrame;
            if (!spriteFrame || !spriteFrame.texture) {
              return false;
            }
          }
          return true;
        }
        _flushAssembler() {
          const 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();
            }
          }
        }
        _applyFontTexture() {
          this.markForUpdateRenderData();
          const font = this._font;
          if (font instanceof BitmapFont) {
            const 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 === 2) {
              this._letterTexture = this._assembler.getAssemblerData();
              this._texture = this._letterTexture;
            } else if (!this._ttfSpriteFrame) {
              this._ttfSpriteFrame = new SpriteFrame();
              this._assemblerData = this._assembler.getAssemblerData();
              const image = new ImageAsset$1(this._assemblerData.canvas);
              const texture = new Texture2D$1();
              texture.image = image;
              this._ttfSpriteFrame.texture = texture;
            }
            if (this.cacheMode !== 2) {
              this._texture = this._ttfSpriteFrame;
            }
            this.changeMaterialForDefine();
          }
        }
        changeMaterialForDefine() {
          if (!this._texture) {
            return;
          }
          let value = false;
          if (this.cacheMode !== 2) {
            const spriteFrame = this._texture;
            const texture = spriteFrame.texture;
            if (texture instanceof TextureBase) {
              const format = texture.getPixelFormat();
              value = format === 1026 || format === 1025 || format === 1024;
            }
          }
          if (value) {
            this._instanceMaterialType = 3;
          } else {
            this._instanceMaterialType = 1;
          }
          this.updateMaterial();
        }
        _updateBlendFunc() {
          super._updateBlendFunc();
        }
      }, _class3$x.HorizontalAlign = HorizontalTextAlignment, _class3$x.VerticalAlign = VerticalTextAlignment, _class3$x.Overflow = Overflow, _class3$x.CacheMode = CacheMode, _class3$x._canvasPool = CanvasPool.getInstance(), _class3$x), (_applyDecoratedDescriptor(_class2$1M.prototype, "horizontalAlign", [_dec3$13], Object.getOwnPropertyDescriptor(_class2$1M.prototype, "horizontalAlign"), _class2$1M.prototype), _applyDecoratedDescriptor(_class2$1M.prototype, "verticalAlign", [_dec4$I], Object.getOwnPropertyDescriptor(_class2$1M.prototype, "verticalAlign"), _class2$1M.prototype), _applyDecoratedDescriptor(_class2$1M.prototype, "overflow", [_dec5$D], Object.getOwnPropertyDescriptor(_class2$1M.prototype, "overflow"), _class2$1M.prototype), _applyDecoratedDescriptor(_class2$1M.prototype, "font", [_dec6$u], Object.getOwnPropertyDescriptor(_class2$1M.prototype, "font"), _class2$1M.prototype), _applyDecoratedDescriptor(_class2$1M.prototype, "cacheMode", [_dec7$n], Object.getOwnPropertyDescriptor(_class2$1M.prototype, "cacheMode"), _class2$1M.prototype), _initializer$1F = applyDecoratedInitializer(_class2$1M.prototype, "_string", [serializable$l], function () {
        return 'label';
      }), _initializer2$1i = applyDecoratedInitializer(_class2$1M.prototype, "_horizontalAlign", [serializable$l], function () {
        return 1;
      }), _initializer3$X = applyDecoratedInitializer(_class2$1M.prototype, "_verticalAlign", [serializable$l], function () {
        return 1;
      }), _initializer4$Q = applyDecoratedInitializer(_class2$1M.prototype, "_actualFontSize", [serializable$l], function () {
        return 0;
      }), _initializer5$D = applyDecoratedInitializer(_class2$1M.prototype, "_fontSize", [serializable$l], function () {
        return 40;
      }), _initializer6$w = applyDecoratedInitializer(_class2$1M.prototype, "_fontFamily", [serializable$l], function () {
        return 'Arial';
      }), _initializer7$n = applyDecoratedInitializer(_class2$1M.prototype, "_lineHeight", [serializable$l], function () {
        return 40;
      }), _initializer8$l = applyDecoratedInitializer(_class2$1M.prototype, "_overflow", [serializable$l], function () {
        return 0;
      }), _initializer9$j = applyDecoratedInitializer(_class2$1M.prototype, "_enableWrapText", [serializable$l], function () {
        return true;
      }), _initializer10$i = applyDecoratedInitializer(_class2$1M.prototype, "_font", [serializable$l], function () {
        return null;
      }), _initializer11$h = applyDecoratedInitializer(_class2$1M.prototype, "_isSystemFontUsed", [serializable$l], function () {
        return true;
      }), _initializer12$g = applyDecoratedInitializer(_class2$1M.prototype, "_spacingX", [serializable$l], function () {
        return 0;
      }), _initializer13$d = applyDecoratedInitializer(_class2$1M.prototype, "_isItalic", [serializable$l], function () {
        return false;
      }), _initializer14$b = applyDecoratedInitializer(_class2$1M.prototype, "_isBold", [serializable$l], function () {
        return false;
      }), _initializer15$8 = applyDecoratedInitializer(_class2$1M.prototype, "_isUnderline", [serializable$l], function () {
        return false;
      }), _initializer16$8 = applyDecoratedInitializer(_class2$1M.prototype, "_underlineHeight", [serializable$l], function () {
        return 2;
      }), _initializer17$5 = applyDecoratedInitializer(_class2$1M.prototype, "_cacheMode", [serializable$l], function () {
        return 0;
      }), _initializer18$5 = applyDecoratedInitializer(_class2$1M.prototype, "_enableOutline", [serializable$l], function () {
        return false;
      }), _initializer19$4 = applyDecoratedInitializer(_class2$1M.prototype, "_outlineColor", [serializable$l], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer20$4 = applyDecoratedInitializer(_class2$1M.prototype, "_outlineWidth", [serializable$l], function () {
        return 2;
      }), _initializer21$4 = applyDecoratedInitializer(_class2$1M.prototype, "_enableShadow", [serializable$l], function () {
        return false;
      }), _initializer22$3 = applyDecoratedInitializer(_class2$1M.prototype, "_shadowColor", [serializable$l], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer23$2 = applyDecoratedInitializer(_class2$1M.prototype, "_shadowOffset", [serializable$l], function () {
        return new Vec2(2, 2);
      }), _initializer24$2 = applyDecoratedInitializer(_class2$1M.prototype, "_shadowBlur", [serializable$l], function () {
        return 2;
      })), _class2$1M)) || _class$25) || _class$25); exports({ Label: Label, LabelComponent: Label });
      cclegacy.Label = Label;

      let _stageOffset = 0;
      const _name2stageID = {};
      var config = {
        addStage(name) {
          if (_name2stageID[name] !== undefined) {
            return;
          }
          const stageID = 1 << _stageOffset;
          _name2stageID[name] = stageID;
          _stageOffset += 1;
        },
        stageID(name) {
          const id = _name2stageID[name];
          if (id === undefined) {
            return -1;
          }
          return id;
        },
        stageIDs(nameList) {
          let key = 0;
          for (const name of nameList) {
            const id = _name2stageID[name];
            if (id !== undefined) {
              key |= id;
            }
          }
          return key;
        }
      };

      function createIA(device, data) {
        if (!data.positions) {
          errorID(16306);
          return null;
        }
        const verts = [];
        const vcount = data.positions.length / 3;
        for (let 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]);
          }
        }
        const vfmt = [];
        vfmt.push(new Attribute("a_position", 32));
        if (data.normals) {
          vfmt.push(new Attribute("a_normal", 32));
        }
        if (data.uvs) {
          vfmt.push(new Attribute("a_texCoord", 21));
        }
        if (data.colors) {
          vfmt.push(new Attribute("a_color", 32));
        }
        const vb = device.createBuffer(new BufferInfo(8 | 2, 1, verts.length * 4, verts.length * 4 / vcount));
        vb.update(new Float32Array(verts));
        let ib = null;
        if (data.indices) {
          ib = device.createBuffer(new BufferInfo(4 | 2, 1, data.indices.length * 2, 2));
          ib.update(new Uint16Array(data.indices));
        }
        return device.createInputAssembler(new InputAssemblerInfo(vfmt, [vb], ib));
      }

      const RenderQueue = {
        "OPAQUE": 0,
        "TRANSPARENT": 1,
        "OVERLAY": 2
      };
      const PassStage = {
        "DEFAULT": 1,
        "FORWARD": 2,
        "SHADOWCAST": 4
      };

      const typeMask = 0xfc000000;
      const bindingMask = 0x03f00000;
      const countMask = 0x000ff000;
      const offsetMask = 0x00000fff;
      const genHandle = (binding, type, count, offset = 0) => type << 26 & typeMask | binding << 20 & bindingMask | count << 12 & countMask | offset & offsetMask;
      const getTypeFromHandle = handle => (handle & typeMask) >>> 26;
      const getBindingFromHandle = handle => (handle & bindingMask) >>> 20;
      const getCountFromHandle = handle => (handle & countMask) >>> 12;
      const getOffsetFromHandle = handle => handle & offsetMask;
      const customizeType = (handle, type) => handle & ~typeMask | type << 26 & typeMask;
      const type2reader = {
        [0]: (a, v, idx = 0) => warnID(12010, idx),
        [5]: (a, v, idx = 0) => a[idx],
        [6]: (a, v, idx = 0) => Vec2.fromArray(v, a, idx),
        [7]: (a, v, idx = 0) => Vec3.fromArray(v, a, idx),
        [8]: (a, v, idx = 0) => Vec4.fromArray(v, a, idx),
        [13]: (a, v, idx = 0) => a[idx],
        [14]: (a, v, idx = 0) => Vec2.fromArray(v, a, idx),
        [15]: (a, v, idx = 0) => Vec3.fromArray(v, a, idx),
        [16]: (a, v, idx = 0) => Vec4.fromArray(v, a, idx),
        [21]: (a, v, idx = 0) => Mat3.fromArray(v, a, idx),
        [25]: (a, v, idx = 0) => Mat4.fromArray(v, a, idx)
      };
      const type2writer = {
        [0]: (a, v, idx = 0) => warnID(12010, idx),
        [5]: (a, v, idx = 0) => a[idx] = v,
        [6]: (a, v, idx = 0) => Vec2.toArray(a, v, idx),
        [7]: (a, v, idx = 0) => Vec3.toArray(a, v, idx),
        [8]: (a, v, idx = 0) => Vec4.toArray(a, v, idx),
        [13]: (a, v, idx = 0) => a[idx] = v,
        [14]: (a, v, idx = 0) => Vec2.toArray(a, v, idx),
        [15]: (a, v, idx = 0) => Vec3.toArray(a, v, idx),
        [16]: (a, v, idx = 0) => Vec4.toArray(a, v, idx),
        [21]: (a, v, idx = 0) => Mat3.toArray(a, v, idx),
        [25]: (a, v, idx = 0) => Mat4.toArray(a, v, idx)
      };
      const type2validator = {
        [5]: v => typeof v === 'number',
        [13]: v => typeof v === 'number',
        [6]: v => !!(v instanceof Vec2),
        [14]: v => !!(v instanceof Vec2),
        [7]: v => !!(v instanceof Vec3),
        [15]: v => !!(v instanceof Vec3),
        [8]: v => !!(v instanceof Vec4),
        [16]: v => !!(v instanceof Vec4 || v instanceof Color$1 || v instanceof Quat),
        [21]: v => !!(v instanceof Mat3),
        [25]: v => !!(v instanceof Mat4)
      };
      const 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 1:
          case 5:
          case 9:
          case 13:
            return defaultValues[0];
          case 2:
          case 6:
          case 10:
          case 14:
            return defaultValues[1];
          case 4:
          case 8:
          case 12:
          case 16:
            return defaultValues[2];
          case 25:
            return defaultValues[3];
          case 28:
            return 'default-texture';
          case 31:
            return 'default-cube-texture';
          case 29:
            return 'default-array-texture';
          case 30:
            return 'default-3d-texture';
        }
        return defaultValues[0];
      }
      function getStringFromType(type) {
        switch (type) {
          case 28:
            return '-texture';
          case 31:
            return '-cube-texture';
          case 29:
            return '-array-texture';
          case 30:
            return '-3d-texture';
          default:
            return '-unknown';
        }
      }
      function overrideMacros(target, source) {
        const entries = Object.entries(source);
        let isDifferent = false;
        for (let 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;
      }

      let BatchingSchemes;
      (function (BatchingSchemes) {
        BatchingSchemes[BatchingSchemes["NONE"] = 0] = "NONE";
        BatchingSchemes[BatchingSchemes["INSTANCING"] = 1] = "INSTANCING";
      })(BatchingSchemes || (BatchingSchemes = {}));
      const Pass = jsb.Pass;
      const proto = Pass.prototype;
      proto.getUniform = function getUniform(handle, out) {
        const val = this._getUniform(handle);
        if (typeof val === 'object') {
          if (val.type) {
            switch (val.type) {
              case 0:
                Vec2.copy(out, val);
                break;
              case 1:
                Vec3.copy(out, val);
                break;
              case 2:
                Vec4.copy(out, val);
                break;
              case 8:
                out.x = val.x;
                out.y = val.y;
                out.z = val.z;
                out.w = val.w;
                break;
              case 4:
                Mat3.copy(out, val);
                break;
              case 5:
                Mat4.copy(out, val);
                break;
              case 3:
                Quat.copy(out, val);
                break;
              default:
                console.error(`getUniform, unknown object type: ${val.type}`);
                break;
            }
          } else {
            console.error(`getUniform, unknown object: ${val}`);
          }
        } else if (typeof val === 'number') {
          out = val;
        } else {
          console.error(`getUniform, not supported: ${val}`);
        }
        return out;
      };

      function getDeviceShaderVersion(device) {
        switch (device.gfxAPI) {
          case 1:
          case 6:
            return 'glsl1';
          case 2:
          case 7:
            return 'glsl3';
          default:
            return 'glsl4';
        }
      }
      const programLib = jsb.ProgramLib.getInstance();
      cclegacy.programLib = programLib;

      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;
      }
      class TextureBufferPool {
        constructor(device) {
          this._format = 0;
          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;
        }
        initialize(info) {
          const 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;
          }
        }
        destroy() {
          for (let i = 0; i < this._chunkCount; ++i) {
            const chunk = this._chunks[i];
            chunk.texture.destroy();
          }
          this._chunks.length = 0;
          this._handles.length = 0;
        }
        alloc(size, chunkIdx) {
          size = roundUp(size, this._alignment);
          let index = -1;
          let start = -1;
          if (chunkIdx !== undefined) {
            index = chunkIdx;
            start = this._findAvailableSpace(size, index);
          }
          if (start < 0) {
            for (let i = 0; i < this._chunkCount; ++i) {
              index = i;
              start = this._findAvailableSpace(size, index);
              if (start >= 0) {
                break;
              }
            }
          }
          if (start >= 0) {
            const chunk = this._chunks[index];
            chunk.start += size;
            const handle = {
              chunkIdx: index,
              start,
              end: start + size,
              texture: chunk.texture
            };
            this._handles.push(handle);
            return handle;
          }
          const targetSize = Math.sqrt(size / this._formatSize);
          const texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          const newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          const texHandle = {
            chunkIdx: this._chunkCount - 1,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        }
        free(handle) {
          for (let 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;
            }
          }
        }
        createChunk(length) {
          const texSize = length * length * this._formatSize;
          debug(`TextureBufferPool: Allocate chunk ${this._chunkCount}, size: ${texSize}, format: ${this._format}`);
          const texture = this._device.createTexture(new TextureInfo(1, 4 | 2, this._format, length, length));
          const chunk = {
            texture,
            size: texSize,
            start: 0,
            end: texSize
          };
          this._chunks[this._chunkCount] = chunk;
          return this._chunkCount++;
        }
        update(handle, buffer) {
          const buffers = [];
          const regions = [];
          const start = handle.start / this._formatSize;
          let remainSize = buffer.byteLength / this._formatSize;
          let offsetX = start % handle.texture.width;
          let offsetY = Math.floor(start / handle.texture.width);
          let copySize = Math.min(handle.texture.width - offsetX, remainSize);
          let 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);
        }
        _findAvailableSpace(size, chunkIdx) {
          const chunk = this._chunks[chunkIdx];
          let isFound = false;
          let start = chunk.start;
          if (start + size <= chunk.size) {
            isFound = true;
          } else {
            start = 0;
            const handles = this._handles.filter(h => h.chunkIdx === chunkIdx).sort((a, b) => a.start - b.start);
            for (let i = 0; i < handles.length; i++) {
              const 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;
        }
        _McDonaldAlloc(size) {
          size = roundUp(size, this._alignment);
          for (let i = 0; i < this._chunkCount; ++i) {
            const chunk = this._chunks[i];
            let isFound = false;
            let 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;
              const handle = {
                chunkIdx: i,
                start,
                end: start + size,
                texture: chunk.texture
              };
              this._handles.push(handle);
              return handle;
            }
          }
          const targetSize = Math.sqrt(size / this._formatSize);
          const texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          const newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          const texHandle = {
            chunkIdx: this._chunkCount,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        }
      }

      class PassInstance extends Pass {
        get parent() {
          return this._parent;
        }
        constructor(parent, owner) {
          super(parent.root);
          this._dontNotify = false;
          this._parent = parent;
          this._owner = owner;
          this._doInit(this._parent, true);
          for (let i = 0; i < this._shaderInfo.blocks.length; i++) {
            const u = this._shaderInfo.blocks[i];
            const block = this._blocks[u.binding];
            const parentBlock = this._parent.blocks[u.binding];
            block.set(parentBlock);
          }
          this._rootBufferDirty = true;
          const paren = this._parent;
          for (let i = 0; i < this._shaderInfo.samplerTextures.length; i++) {
            const u = this._shaderInfo.samplerTextures[i];
            for (let j = 0; j < u.count; j++) {
              const sampler = paren._descriptorSet.getSampler(u.binding, j);
              const texture = paren._descriptorSet.getTexture(u.binding, j);
              this._descriptorSet.bindSampler(u.binding, sampler, j);
              this._descriptorSet.bindTexture(u.binding, texture, j);
            }
          }
          super.tryCompile();
        }
        overridePipelineStates(original, overrides) {
          this._bs.reset();
          this._rs.reset();
          this._dss.reset();
          Pass.fillPipelineInfo(this, original);
          Pass.fillPipelineInfo(this, overrides);
          this._onStateChange();
        }
        tryCompile(defineOverrides) {
          if (defineOverrides) {
            if (!overrideMacros(this._defines, defineOverrides)) {
              return false;
            }
          }
          const res = super.tryCompile();
          this._onStateChange();
          return res;
        }
        beginChangeStatesSilently() {
          this._dontNotify = true;
        }
        endChangeStatesSilently() {
          this._dontNotify = false;
        }
        _syncBatchingScheme() {
          this._defines.USE_INSTANCING = false;
          this._batchingScheme = 0;
        }
        _onStateChange() {
          this._hash = Pass.getPassHash(this);
          this._owner.onPassStateChange(this._dontNotify);
        }
      }

      const NativeBufferPool = jsb.NativeBufferPool;
      jsb.NativeObjectPool;
      jsb.NativeBufferAllocator;

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

      const renderSceneProto = jsb.RenderScene.prototype;
      Object.defineProperty(renderSceneProto, 'mainLight', {
        enumerable: true,
        configurable: true,
        get() {
          return this.getMainLight();
        }
      });
      const RenderScene = jsb.RenderScene;

      const RenderWindow = jsb.RenderWindow;

      Enum({
        Low_256x256: 256,
        Medium_512x512: 512,
        High_1024x1024: 1024,
        Ultra_2048x2048: 2048
      });
      const ShadowType = Enum({
        Planar: 0,
        ShadowMap: 1
      });
      Enum({
        HARD: 0,
        SOFT: 1,
        SOFT_2X: 2,
        SOFT_4X: 3
      });
      Enum({
        LEVEL_1: 1,
        LEVEL_2: 2,
        LEVEL_3: 3,
        LEVEL_4: 4
      });
      Enum({
        NONE: 1,
        RemoveDuplicates: 2,
        DisableRotationFix: 3
      });
      const SHADOW_TYPE_NONE = ShadowType.ShadowMap + 1;
      class Shadows {
        constructor() {
          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._planeBias = 1.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;
        }
        get enabled() {
          return this._enabled;
        }
        set enabled(val) {
          this._enabled = val;
          this.activate();
        }
        get type() {
          return this._type;
        }
        set type(val) {
          this._type = this.enabled ? val : SHADOW_TYPE_NONE;
          this.activate();
        }
        get normal() {
          return this._normal;
        }
        set normal(val) {
          Vec3.copy(this._normal, val);
        }
        get distance() {
          return this._distance;
        }
        set distance(val) {
          this._distance = val;
        }
        get planeBias() {
          return this._planeBias;
        }
        set planeBias(val) {
          this._planeBias = val;
        }
        get shadowColor() {
          return this._shadowColor;
        }
        set shadowColor(color) {
          this._shadowColor = color;
        }
        get size() {
          return this._size;
        }
        set size(val) {
          this._size.set(val);
        }
        get shadowMapDirty() {
          return this._shadowMapDirty;
        }
        set shadowMapDirty(val) {
          this._shadowMapDirty = val;
        }
        get matLight() {
          return this._matLight;
        }
        get material() {
          return this._material;
        }
        get instancingMaterial() {
          return this._instancingMaterial;
        }
        getPlanarShader(patches) {
          if (!this._material) {
            this._material = new Material$1();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          const passes = this._material.passes;
          {
            assert(passes.length > 0, 'passes should not be empty!');
          }
          return passes.length > 0 ? passes[0].getShaderVariant(patches) : null;
        }
        initialize(shadowsInfo) {
          this._enabled = shadowsInfo.enabled;
          this._type = this.enabled ? shadowsInfo.type : SHADOW_TYPE_NONE;
          this.normal = shadowsInfo.planeDirection;
          this.distance = shadowsInfo.planeHeight;
          this.planeBias = shadowsInfo.planeBias;
          this.shadowColor = shadowsInfo.shadowColor;
          this.maxReceived = shadowsInfo.maxReceived;
          if (shadowsInfo.shadowMapSize !== this._size.x) {
            this.size.set(shadowsInfo.shadowMapSize, shadowsInfo.shadowMapSize);
            this._shadowMapDirty = true;
          }
        }
        activate() {
          if (this._enabled) {
            if (this.type === ShadowType.Planar) {
              this._updatePlanarInfo();
            } else {
              const root = cclegacy.director.root;
              const pipeline = root.pipeline;
              pipeline.macros.CC_SHADOW_TYPE = 2;
              root.onGlobalPipelineStateChanged();
            }
          } else {
            const root = cclegacy.director.root;
            const pipeline = root.pipeline;
            pipeline.macros.CC_SHADOW_TYPE = 0;
            root.onGlobalPipelineStateChanged();
          }
        }
        _updatePlanarInfo() {
          if (!this._material) {
            this._material = new Material$1();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          const root = cclegacy.director.root;
          const pipeline = root.pipeline;
          pipeline.macros.CC_SHADOW_TYPE = 1;
          root.onGlobalPipelineStateChanged();
        }
        destroy() {
          if (this._material) {
            this._material.destroy();
          }
          if (this._instancingMaterial) {
            this._instancingMaterial.destroy();
          }
          this.fixedSphere.destroy();
        }
      }
      Shadows.MAX_FAR = 2000.0;
      Shadows.COEFFICIENT_OF_EXPANSION = 2.0 * Math.sqrt(3.0);
      cclegacy.Shadows = Shadows;

      removeProperty(RenderScene.prototype, 'RenderScene.prototype', [{
        name: 'raycastUI2DNode'
      }, {
        name: 'raycastUINode'
      }]);
      removeProperty(RenderScene.prototype, 'RenderScene.prototype', [{
        name: 'raycastAll',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastAllModels',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastSingleModel',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastAllCanvas',
        suggest: 'using intersect.rayAABB in geometry'
      }, {
        name: 'rayResultCanvas'
      }, {
        name: 'rayResultModels'
      }, {
        name: 'rayResultAll'
      }, {
        name: 'rayResultSingleModel'
      }]);
      removeProperty(Model.prototype, 'Model.prototype', [{
        name: 'isInstancingEnabled'
      }, {
        name: 'instancedAttributes'
      }]);
      const CameraVisFlags = {};
      removeProperty(CameraVisFlags, 'CameraVisFlags', [{
        name: 'GENERAL'
      }]);
      replaceProperty(CameraVisFlags, 'CameraVisFlags', [{
        name: 'PROFILER',
        newName: 'PROFILER',
        target: Layers.BitMask,
        targetName: 'PROFILER'
      }, {
        name: 'GIZMOS',
        newName: 'GIZMOS',
        target: Layers.BitMask,
        targetName: 'GIZMOS'
      }, {
        name: 'EDITOR',
        newName: 'EDITOR',
        target: Layers.BitMask,
        targetName: 'EDITOR'
      }, {
        name: 'UI',
        newName: 'UI',
        target: Layers.BitMask,
        targetName: 'UI_3D'
      }, {
        name: 'UI2D',
        newName: 'UI2D',
        target: Layers.BitMask,
        targetName: 'UI_2D'
      }]);
      legacyCC.CameraVisFlags = CameraVisFlags;
      const VisibilityFlags = {};
      removeProperty(VisibilityFlags, 'VisibilityFlags', [{
        name: 'GENERAL'
      }]);
      replaceProperty(VisibilityFlags, 'VisibilityFlags', [{
        name: 'ALWALS',
        newName: 'ALWALS',
        target: Layers.Enum,
        targetName: 'ALWALS'
      }, {
        name: 'PROFILER',
        newName: 'PROFILER',
        target: Layers.Enum,
        targetName: 'PROFILER'
      }, {
        name: 'GIZMOS',
        newName: 'GIZMOS',
        target: Layers.Enum,
        targetName: 'GIZMOS'
      }, {
        name: 'EDITOR',
        newName: 'EDITOR',
        target: Layers.Enum,
        targetName: 'EDITOR'
      }, {
        name: 'UI',
        newName: 'UI',
        target: Layers.Enum,
        targetName: 'UI_3D'
      }, {
        name: 'UI2D',
        newName: 'UI2D',
        target: Layers.Enum,
        targetName: 'UI_2D'
      }]);
      legacyCC.VisibilityFlags = VisibilityFlags;
      replaceProperty(Pass.prototype, 'Pass.prototype', [{
        name: 'getBindingTypeFromHandle',
        newName: 'getDescriptorTypeFromHandle'
      }]);
      removeProperty(Camera$1.prototype, 'Camera.prototype', [{
        name: 'getSplitFrustum'
      }, {
        name: 'setMatView'
      }, {
        name: 'setMatViewInv'
      }, {
        name: 'setMatProjInv'
      }, {
        name: 'setMatViewProjInv'
      }, {
        name: 'setMatProj'
      }, {
        name: 'setMatViewProj'
      }, {
        name: 'getMatViewInv'
      }]);
      removeProperty(Shadows.prototype, 'Shadows.prototype', [{
        name: 'aspect'
      }, {
        name: 'selfShadow'
      }, {
        name: 'linear'
      }, {
        name: 'packing'
      }, {
        name: 'autoAdapt'
      }, {
        name: 'fixedArea'
      }, {
        name: 'pcf'
      }, {
        name: 'bias'
      }, {
        name: 'normalBias'
      }, {
        name: 'near'
      }, {
        name: 'far'
      }, {
        name: 'shadowDistance'
      }, {
        name: 'invisibleOcclusionRange'
      }, {
        name: 'orthoSize'
      }, {
        name: 'saturation'
      }]);
      removeProperty(SpotLight.prototype, 'SpotLight.prototype', [{
        name: 'aspect'
      }]);
      replaceProperty(SubModel.prototype, 'SubModel.prototype', [{
        name: 'subMeshData',
        newName: 'subMesh'
      }]);
      removeProperty(SubModel.prototype, 'SubModel.prototype', [{
        name: 'getSubModel',
        suggest: 'Use `subModels[i]` instead'
      }, {
        name: 'subModelNum',
        suggest: 'Use `subModels.length` instead'
      }]);

      const addStage = config.addStage;

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

      const LineCap = {
        "BUTT": 0,
        "ROUND": 1,
        "SQUARE": 2
      };
      ccenum(LineCap);
      const LineJoin = {
        "BEVEL": 0,
        "ROUND": 1,
        "MITER": 2
      };
      ccenum(LineJoin);
      const PointFlags = {
        "PT_CORNER": 1,
        "PT_LEFT": 2,
        "PT_BEVEL": 4,
        "PT_INNERBEVEL": 8
      };
      ccenum(PointFlags);

      const PI$1 = Math.PI;
      const min$1 = Math.min;
      const max$1 = Math.max;
      const cos$1 = Math.cos;
      const sin$1 = Math.sin;
      const abs = Math.abs;
      const sign = Math.sign;
      const KAPPA90 = 0.5522847493;
      function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
        counterclockwise = counterclockwise || false;
        let a = 0;
        let da = 0;
        let hda = 0;
        let kappa = 0;
        let dx = 0;
        let dy = 0;
        let x = 0;
        let y = 0;
        let tanx = 0;
        let tany = 0;
        let px = 0;
        let py = 0;
        let ptanx = 0;
        let ptany = 0;
        let i = 0;
        let 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 {
          const rx = min$1(r, abs(w) * 0.5) * sign(w);
          const 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) {
        let x12 = 0;
        let y12 = 0;
        let x23 = 0;
        let y23 = 0;
        let x34 = 0;
        let y34 = 0;
        let x123 = 0;
        let y123 = 0;
        let x234 = 0;
        let y234 = 0;
        let x1234 = 0;
        let y1234 = 0;
        let dx = 0;
        let dy = 0;
        let d2 = 0;
        let 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 | 4 : 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);
      }

      let Point$1 = class Point extends Vec2 {
        constructor(x, y) {
          super(x, y);
          this.dx = 0;
          this.dy = 0;
          this.dmx = 0;
          this.dmy = 0;
          this.flags = 0;
          this.len = 0;
        }
        reset() {
          this.dx = 0;
          this.dy = 0;
          this.dmx = 0;
          this.dmy = 0;
          this.flags = 0;
          this.len = 0;
        }
      };
      class Path {
        constructor() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points = [];
        }
        reset() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points.length = 0;
        }
      }
      class Impl {
        constructor(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 = 0;
          this.strokeColor = Color$1.BLACK.clone();
          this.lineJoin = 2;
          this.lineWidth = 0;
          this.pointsOffset = 0;
          this._commandX = 0;
          this._commandY = 0;
          this._points = [];
          this._renderDataList = [];
          this._curPath = null;
          this._comp = comp;
        }
        moveTo(x, y) {
          if (this.updatePathOffset) {
            this.pathOffset = this.pathLength;
            this.updatePathOffset = false;
          }
          this._addPath();
          this.addPoint(x, y, 1);
          this._commandX = x;
          this._commandY = y;
        }
        lineTo(x, y) {
          this.addPoint(x, y, 1);
          this._commandX = x;
          this._commandY = y;
        }
        bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          const path = this._curPath;
          const 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, 1);
          this._commandX = x;
          this._commandY = y;
        }
        quadraticCurveTo(cx, cy, x, y) {
          const x0 = this._commandX;
          const 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);
        }
        arc(cx, cy, r, startAngle, endAngle, counterclockwise) {
          arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
        }
        ellipse(cx, cy, rx, ry) {
          ellipse(this, cx, cy, rx, ry);
          this._curPath.complex = false;
        }
        circle(cx, cy, r) {
          ellipse(this, cx, cy, r, r);
          this._curPath.complex = false;
        }
        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;
        }
        roundRect(x, y, w, h, r) {
          roundRect(this, x, y, w, h, r);
          this._curPath.complex = false;
        }
        clear() {
          this.pathLength = 0;
          this.pathOffset = 0;
          this.pointsOffset = 0;
          this.dataOffset = 0;
          this._curPath = null;
          this.paths.length = 0;
          this._points.length = 0;
          const dataList = this._renderDataList;
          for (let i = 0, l = dataList.length; i < l; i++) {
            const data = dataList[i];
            if (!data) {
              continue;
            }
            MeshRenderData.remove(data);
            data.removeRenderDrawInfo(this._comp);
          }
          this._renderDataList.length = 0;
        }
        close() {
          this._curPath.closed = true;
        }
        requestRenderData() {
          const renderData = MeshRenderData.add();
          this._renderDataList.push(renderData);
          {
            renderData.initRenderDrawInfo(this._comp, 1);
            renderData.material = this._comp.getMaterialInstance(0);
            this._comp.setRenderData(renderData);
          }
          return renderData;
        }
        getRenderDataList() {
          if (this._renderDataList.length === 0) {
            this.requestRenderData();
          }
          return this._renderDataList;
        }
        addPoint(x, y, flags) {
          const path = this._curPath;
          if (!path) {
            return;
          }
          const points = this._points;
          const pathPoints = path.points;
          const offset = this.pointsOffset++;
          let pt = points[offset];
          if (!pt) {
            pt = new Point$1(x, y);
            points.push(pt);
          } else {
            pt.x = x;
            pt.y = y;
          }
          pt.flags = flags;
          pathPoints.push(pt);
        }
        _addPath() {
          const offset = this.pathLength;
          let path = this.paths[offset];
          if (!path) {
            path = new Path();
            this.paths.push(path);
          } else {
            path.reset();
          }
          this.pathLength++;
          this._curPath = path;
          return path;
        }
      }

      var _dec$24, _dec2$1t, _dec3$12, _dec4$H, _class$24, _class2$1L, _initializer$1E, _initializer2$1h, _initializer3$W, _initializer4$P, _initializer5$C, _initializer6$v, _class3$w;
      const attributes = vfmtPosColor.concat([new Attribute('a_dist', 11)]);
      const componentPerVertex = getComponentPerVertex(attributes);
      const stride = getAttributeStride(attributes);
      let Graphics = (_dec$24 = ccclass$H('cc.Graphics'), _dec2$1t = executionOrder$1(110), _dec3$12 = type$a(LineJoin), _dec4$H = type$a(LineCap), _dec$24(_class$24 = _dec2$1t(_class$24 = (_class2$1L = (_class3$w = class Graphics extends UIRenderer {
        get lineWidth() {
          return this._lineWidth;
        }
        set lineWidth(value) {
          this._lineWidth = value;
          if (!this.impl) {
            return;
          }
          this.impl.lineWidth = value;
        }
        get lineJoin() {
          return this._lineJoin;
        }
        set lineJoin(value) {
          this._lineJoin = value;
          if (!this.impl) {
            return;
          }
          this.impl.lineJoin = value;
        }
        get lineCap() {
          return this._lineCap;
        }
        set lineCap(value) {
          this._lineCap = value;
          if (!this.impl) {
            return;
          }
          this.impl.lineCap = value;
        }
        get strokeColor() {
          return this._strokeColor;
        }
        set strokeColor(value) {
          if (!this.impl) {
            return;
          }
          this._strokeColor.set(value);
          this.impl.strokeColor = this._strokeColor;
        }
        get fillColor() {
          return this._fillColor;
        }
        set fillColor(value) {
          if (!this.impl) {
            return;
          }
          this._fillColor.set(value);
          this.impl.fillColor = this._fillColor;
        }
        get miterLimit() {
          return this._miterLimit;
        }
        set miterLimit(value) {
          this._miterLimit = value;
        }
        get color() {
          return this._color;
        }
        set color(value) {
          if (this._color === value) {
            return;
          }
          this._color.set(value);
        }
        get graphicsNativeProxy() {
          return this._graphicsNativeProxy;
        }
        constructor() {
          super();
          this.impl = null;
          this.model = null;
          this._lineWidth = _initializer$1E && _initializer$1E();
          this._strokeColor = _initializer2$1h && _initializer2$1h();
          this._lineJoin = _initializer3$W && _initializer3$W();
          this._lineCap = _initializer4$P && _initializer4$P();
          this._fillColor = _initializer5$C && _initializer5$C();
          this._miterLimit = _initializer6$v && _initializer6$v();
          this._isDrawing = false;
          this._isNeedUploadData = true;
          this._graphicsUseSubMeshes = [];
          this._instanceMaterialType = 0;
          this.impl = new Impl(this);
          {
            this._graphicsNativeProxy = new NativeUIModelProxy();
          }
        }
        onRestore() {
          if (!this.impl) {
            this._flushAssembler();
          }
        }
        onLoad() {
          super.onLoad();
          {
            this._graphicsNativeProxy.initModel(this.node);
            this.model = this._graphicsNativeProxy.getModel();
          }
          this._flushAssembler();
        }
        onEnable() {
          super.onEnable();
          this._updateMtlForGraphics();
        }
        onDestroy() {
          this._sceneGetter = null;
          {
            this._graphicsNativeProxy.destroy();
            this.model = null;
          }
          if (this.impl) {
            this._isDrawing = false;
            this.impl.clear();
            this.impl = null;
          }
          super.onDestroy();
        }
        moveTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.moveTo(x, y);
        }
        lineTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.lineTo(x, y);
        }
        bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
        }
        quadraticCurveTo(cx, cy, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.quadraticCurveTo(cx, cy, x, y);
        }
        arc(cx, cy, r, startAngle, endAngle, counterclockwise) {
          if (!this.impl) {
            return;
          }
          this.impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
        }
        ellipse(cx, cy, rx, ry) {
          if (!this.impl) {
            return;
          }
          this.impl.ellipse(cx, cy, rx, ry);
        }
        circle(cx, cy, r) {
          if (!this.impl) {
            return;
          }
          this.impl.circle(cx, cy, r);
        }
        rect(x, y, w, h) {
          if (!this.impl) {
            return;
          }
          this.impl.rect(x, y, w, h);
        }
        roundRect(x, y, w, h, r) {
          if (!this.impl) {
            return;
          }
          this.impl.roundRect(x, y, w, h, r);
        }
        fillRect(x, y, w, h) {
          this.rect(x, y, w, h);
          this.fill();
        }
        clear() {
          if (!this.impl) {
            return;
          }
          this.impl.clear();
          this._isDrawing = false;
          {
            this._graphicsNativeProxy.clear();
          }
          this.markForUpdateRenderData();
        }
        close() {
          if (!this.impl) {
            return;
          }
          this.impl.close();
        }
        stroke() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.stroke(this);
        }
        fill() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.fill(this);
        }
        _updateMtlForGraphics() {
          let 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
            });
          }
        }
        activeSubModel(idx) {
          if (!this.model) {
            warnID(4500, this.node.name);
            return;
          }
          if (this.model.subModels.length <= idx) {
            const gfxDevice = deviceManager.gfxDevice;
            const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(8 | 2, 1, 65535 * stride, stride));
            const indexBuffer = gfxDevice.createBuffer(new BufferInfo(4 | 2, 1, 65535 * 2 * 2, 2));
            const renderMesh = new RenderingSubMesh([vertexBuffer], attributes, 7, indexBuffer);
            renderMesh.subMeshIdx = 0;
            this.model.initSubModel(idx, renderMesh, this.getMaterialInstance(0));
            this._graphicsUseSubMeshes.push(renderMesh);
          }
        }
        _uploadData() {
          const impl = this.impl;
          if (!impl) {
            return;
          }
          const renderDataList = impl && impl.getRenderDataList();
          if (renderDataList.length <= 0 || !this.model) {
            return;
          }
          const subModelList = this.model.subModels;
          for (let i = 0; i < renderDataList.length; i++) {
            const renderData = renderDataList[i];
            const ia = subModelList[i].inputAssembler;
            if (renderData.lastFilledVertex === renderData.vertexStart) {
              continue;
            }
            const vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
            ia.vertexBuffers[0].update(vb);
            ia.vertexCount = renderData.vertexStart;
            const 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;
        }
        _render(render) {
          if (this._isNeedUploadData) {
            if (this.impl) {
              const renderDataList = this.impl.getRenderDataList();
              const len = this.model.subModels.length;
              if (renderDataList.length > len) {
                for (let i = len; i < renderDataList.length; i++) {
                  this.activeSubModel(i);
                }
              }
            }
            this._uploadData();
          }
          render.commitModel(this, this.model, this.getMaterialInstance(0));
        }
        _flushAssembler() {
          const assembler = Graphics.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
        }
        _canRender() {
          if (!super._canRender()) {
            return false;
          }
          {
            return this._isDrawing;
          }
        }
        updateRenderer() {
          super.updateRenderer();
          {
            if (this._isNeedUploadData) {
              if (this.impl) {
                const renderDataList = this.impl.getRenderDataList();
                for (let i = 0; i < renderDataList.length; i++) {
                  renderDataList[i].setRenderDrawInfoAttributes();
                }
                this._graphicsNativeProxy.activeSubModels();
              }
              this._graphicsNativeProxy.uploadData();
              this._isNeedUploadData = false;
            }
          }
        }
        createRenderEntity() {
          return new RenderEntity(1);
        }
      }, _class3$w.LineJoin = LineJoin, _class3$w.LineCap = LineCap, _class3$w), (_applyDecoratedDescriptor(_class2$1L.prototype, "lineJoin", [_dec3$12], Object.getOwnPropertyDescriptor(_class2$1L.prototype, "lineJoin"), _class2$1L.prototype), _applyDecoratedDescriptor(_class2$1L.prototype, "lineCap", [_dec4$H], Object.getOwnPropertyDescriptor(_class2$1L.prototype, "lineCap"), _class2$1L.prototype), _applyDecoratedDescriptor(_class2$1L.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$1L.prototype, "color"), _class2$1L.prototype), _initializer$1E = applyDecoratedInitializer(_class2$1L.prototype, "_lineWidth", [serializable$l], function () {
        return 1;
      }), _initializer2$1h = applyDecoratedInitializer(_class2$1L.prototype, "_strokeColor", [serializable$l], function () {
        return Color$1.BLACK.clone();
      }), _initializer3$W = applyDecoratedInitializer(_class2$1L.prototype, "_lineJoin", [serializable$l], function () {
        return 2;
      }), _initializer4$P = applyDecoratedInitializer(_class2$1L.prototype, "_lineCap", [serializable$l], function () {
        return 0;
      }), _initializer5$C = applyDecoratedInitializer(_class2$1L.prototype, "_fillColor", [serializable$l], function () {
        return Color$1.WHITE.clone();
      }), _initializer6$v = applyDecoratedInitializer(_class2$1L.prototype, "_miterLimit", [serializable$l], function () {
        return 10;
      })), _class2$1L)) || _class$24) || _class$24); exports({ Graphics: Graphics, GraphicsComponent: Graphics });
      cclegacy.Graphics = Graphics;

      var _dec$23, _dec2$1s, _dec3$11, _dec4$G, _dec5$C, _dec6$t, _dec7$m, _class$23, _class2$1K, _initializer$1D, _initializer2$1g, _initializer3$V, _initializer4$O, _initializer5$B, _initializer6$u, _initializer7$m, _initializer8$k, _initializer9$i, _initializer10$h, _class3$v;
      const SpriteType = {
        "SIMPLE": 0,
        "SLICED": 1,
        "TILED": 2,
        "FILLED": 3
      };
      ccenum(SpriteType);
      const FillType = {
        "HORIZONTAL": 0,
        "VERTICAL": 1,
        "RADIAL": 2
      };
      ccenum(FillType);
      const SizeMode$1 = {
        "CUSTOM": 0,
        "TRIMMED": 1,
        "RAW": 2
      };
      ccenum(SizeMode$1);
      const SpriteEventType = {
        "SPRITE_FRAME_CHANGED": "spriteframe-changed"
      };
      let Sprite = (_dec$23 = ccclass$H('cc.Sprite'), _dec2$1s = executionOrder$1(110), _dec3$11 = type$a(SpriteAtlas), _dec4$G = type$a(SpriteFrame), _dec5$C = type$a(SpriteType), _dec6$t = type$a(FillType), _dec7$m = type$a(SizeMode$1), _dec$23(_class$23 = _dec2$1s(_class$23 = (_class2$1K = (_class3$v = class Sprite extends UIRenderer {
        constructor() {
          super();
          this._spriteFrame = _initializer$1D && _initializer$1D();
          this._type = _initializer2$1g && _initializer2$1g();
          this._fillType = _initializer3$V && _initializer3$V();
          this._sizeMode = _initializer4$O && _initializer4$O();
          this._fillCenter = _initializer5$B && _initializer5$B();
          this._fillStart = _initializer6$u && _initializer6$u();
          this._fillRange = _initializer7$m && _initializer7$m();
          this._isTrimmedMode = _initializer8$k && _initializer8$k();
          this._useGrayscale = _initializer9$i && _initializer9$i();
          this._atlas = _initializer10$h && _initializer10$h();
        }
        get spriteAtlas() {
          return this._atlas;
        }
        set spriteAtlas(value) {
          if (this._atlas === value) {
            return;
          }
          this._atlas = value;
        }
        get spriteFrame() {
          return this._spriteFrame;
        }
        set spriteFrame(value) {
          if (this._spriteFrame === value) {
            return;
          }
          const lastSprite = this._spriteFrame;
          this._spriteFrame = value;
          this.markForUpdateRenderData();
          this._applySpriteFrame(lastSprite);
        }
        get type() {
          return this._type;
        }
        set type(value) {
          if (this._type !== value) {
            this._type = value;
            this._flushAssembler();
          }
        }
        get fillType() {
          return this._fillType;
        }
        set fillType(value) {
          if (this._fillType !== value) {
            if (value === 2 || this._fillType === 2) {
              this.destroyRenderData();
            } else if (this.renderData) {
              this.markForUpdateRenderData(true);
            }
          }
          this._fillType = value;
          this._flushAssembler();
        }
        get fillCenter() {
          return this._fillCenter;
        }
        set fillCenter(value) {
          this._fillCenter.x = value.x;
          this._fillCenter.y = value.y;
          if (this._type === 3 && this.renderData) {
            this.markForUpdateRenderData();
          }
        }
        get fillStart() {
          return this._fillStart;
        }
        set fillStart(value) {
          this._fillStart = clamp$1(value, 0, 1);
          if (this._type === 3 && this.renderData) {
            this.markForUpdateRenderData();
            this._updateUVs();
          }
        }
        get fillRange() {
          return this._fillRange;
        }
        set fillRange(value) {
          this._fillRange = clamp$1(value, -1, 1);
          if (this._type === 3 && this.renderData) {
            this.markForUpdateRenderData();
            this._updateUVs();
          }
        }
        get trim() {
          return this._isTrimmedMode;
        }
        set trim(value) {
          if (this._isTrimmedMode === value) {
            return;
          }
          this._isTrimmedMode = value;
          if (this._type === 0 && this.renderData) {
            this.markForUpdateRenderData(true);
          }
        }
        get grayscale() {
          return this._useGrayscale;
        }
        set grayscale(value) {
          if (this._useGrayscale === value) {
            return;
          }
          this._useGrayscale = value;
          this.changeMaterialForDefine();
          this.updateMaterial();
        }
        get sizeMode() {
          return this._sizeMode;
        }
        set sizeMode(value) {
          if (this._sizeMode === value) {
            return;
          }
          this._sizeMode = value;
          if (value !== 0) {
            this._applySpriteSize();
          }
        }
        __preload() {
          this.changeMaterialForDefine();
          super.__preload();
        }
        onEnable() {
          super.onEnable();
          this._activateMaterial();
          const spriteFrame = this._spriteFrame;
          if (spriteFrame) {
            this._updateUVs();
            if (this._type === 1) {
              spriteFrame.on("uv_updated", this._updateUVs, this);
            }
          }
        }
        onDisable() {
          super.onDisable();
          if (this._spriteFrame && this._type === 1) {
            this._spriteFrame.off("uv_updated", this._updateUVs, this);
          }
        }
        onDestroy() {
          super.onDestroy();
        }
        changeSpriteFrameFromAtlas(name) {
          if (!this._atlas) {
            warnID(16377);
            return;
          }
          const sprite = this._atlas.getSpriteFrame(name);
          this.spriteFrame = sprite;
        }
        changeMaterialForDefine() {
          let texture;
          const lastInstanceMaterialType = this._instanceMaterialType;
          if (this._spriteFrame) {
            texture = this._spriteFrame.texture;
          }
          let value = false;
          if (texture instanceof TextureBase) {
            const format = texture.getPixelFormat();
            value = format === 1026 || format === 1025 || format === 1024;
          }
          if (value && this.grayscale) {
            this._instanceMaterialType = 4;
          } else if (value) {
            this._instanceMaterialType = 3;
          } else if (this.grayscale) {
            this._instanceMaterialType = 2;
          } else {
            this._instanceMaterialType = 1;
          }
          if (lastInstanceMaterialType !== this._instanceMaterialType) {
            this.updateMaterial();
          }
        }
        _updateBuiltinMaterial() {
          let mat = super._updateBuiltinMaterial();
          if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
            const renderMat = new Material$1();
            renderMat.copy(mat, {
              defines: {
                SAMPLE_FROM_RT: true
              }
            });
            mat = renderMat;
          }
          return mat;
        }
        _render(render) {
          render.commitComp(this, this.renderData, this._spriteFrame, this._assembler, null);
        }
        _canRender() {
          if (!super._canRender()) {
            return false;
          }
          const spriteFrame = this._spriteFrame;
          if (!spriteFrame || !spriteFrame.texture) {
            return false;
          }
          return true;
        }
        _flushAssembler() {
          const 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 === 1) {
              this._spriteFrame.on("uv_updated", this._updateUVs, this);
            } else {
              this._spriteFrame.off("uv_updated", this._updateUVs, this);
            }
          }
        }
        _applySpriteSize() {
          if (this._spriteFrame) {
            {
              if (2 === this._sizeMode) {
                const size = this._spriteFrame.originalSize;
                this.node._uiProps.uiTransformComp.setContentSize(size);
              } else if (1 === this._sizeMode) {
                const rect = this._spriteFrame.rect;
                this.node._uiProps.uiTransformComp.setContentSize(rect.width, rect.height);
              }
            }
          }
        }
        _resized() {
          {
            return;
          }
        }
        _activateMaterial() {
          const spriteFrame = this._spriteFrame;
          const material = this.getRenderMaterial(0);
          if (spriteFrame) {
            if (material) {
              this.markForUpdateRenderData();
            }
          }
          if (this.renderData) {
            this.renderData.material = material;
          }
        }
        _updateUVs() {
          if (this._assembler) {
            this._assembler.updateUVs(this);
          }
        }
        _applySpriteFrame(oldFrame) {
          const spriteFrame = this._spriteFrame;
          if (oldFrame && this._type === 1) {
            oldFrame.off("uv_updated", this._updateUVs, this);
          }
          let textureChanged = false;
          if (spriteFrame) {
            if (!oldFrame || oldFrame.texture !== spriteFrame.texture) {
              textureChanged = true;
            }
            if (textureChanged) {
              if (this.renderData) this.renderData.textureDirty = true;
              const oldIsRT = oldFrame ? oldFrame.texture instanceof RenderTexture : false;
              const newIsRT = spriteFrame.texture instanceof RenderTexture;
              if (oldIsRT !== newIsRT) {
                this._instanceMaterialType = -1;
              }
              this.changeMaterialForDefine();
            }
            this._applySpriteSize();
            if (this._type === 1) {
              spriteFrame.on("uv_updated", this._updateUVs, this);
            }
          }
        }
        _applyAtlas(spriteFrame) {
          return;
        }
      }, _class3$v.FillType = FillType, _class3$v.Type = SpriteType, _class3$v.SizeMode = SizeMode$1, _class3$v.EventType = SpriteEventType, _class3$v), (_applyDecoratedDescriptor(_class2$1K.prototype, "spriteAtlas", [_dec3$11], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "spriteAtlas"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "spriteFrame", [_dec4$G], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "spriteFrame"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "type", [_dec5$C], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "type"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "fillType", [_dec6$t], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "fillType"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "sizeMode", [_dec7$m], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "sizeMode"), _class2$1K.prototype), _initializer$1D = applyDecoratedInitializer(_class2$1K.prototype, "_spriteFrame", [serializable$l], function () {
        return null;
      }), _initializer2$1g = applyDecoratedInitializer(_class2$1K.prototype, "_type", [serializable$l], function () {
        return 0;
      }), _initializer3$V = applyDecoratedInitializer(_class2$1K.prototype, "_fillType", [serializable$l], function () {
        return 0;
      }), _initializer4$O = applyDecoratedInitializer(_class2$1K.prototype, "_sizeMode", [serializable$l], function () {
        return 1;
      }), _initializer5$B = applyDecoratedInitializer(_class2$1K.prototype, "_fillCenter", [serializable$l], function () {
        return new Vec2(0, 0);
      }), _initializer6$u = applyDecoratedInitializer(_class2$1K.prototype, "_fillStart", [serializable$l], function () {
        return 0;
      }), _initializer7$m = applyDecoratedInitializer(_class2$1K.prototype, "_fillRange", [serializable$l], function () {
        return 0;
      }), _initializer8$k = applyDecoratedInitializer(_class2$1K.prototype, "_isTrimmedMode", [serializable$l], function () {
        return true;
      }), _initializer9$i = applyDecoratedInitializer(_class2$1K.prototype, "_useGrayscale", [serializable$l], function () {
        return false;
      }), _initializer10$h = applyDecoratedInitializer(_class2$1K.prototype, "_atlas", [serializable$l], function () {
        return null;
      })), _class2$1K)) || _class$23) || _class$23); exports({ Sprite: Sprite, SpriteComponent: Sprite });
      cclegacy.Sprite = Sprite;

      var _dec$22, _dec2$1r, _dec3$10, _class$22, _class2$1J, _initializer$1C, _initializer2$1f, _initializer3$U, _initializer4$N, _class3$u;
      const _worldMatrix = new Mat4();
      const _vec2_temp$1 = new Vec2();
      const _mat4_temp$4 = new Mat4();
      const _circlePoints = [];
      function _calculateCircle(center, radius, segments) {
        _circlePoints.length = 0;
        const anglePerStep = Math.PI * 2 / segments;
        for (let 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;
      }
      const MaskType = {
        "GRAPHICS_RECT": 0,
        "GRAPHICS_ELLIPSE": 1,
        "GRAPHICS_STENCIL": 2,
        "SPRITE_STENCIL": 3
      };
      ccenum(MaskType);
      const SEGMENTS_MIN = 3;
      const SEGMENTS_MAX = 10000;
      let Mask = (_dec$22 = ccclass$H('cc.Mask'), _dec2$1r = executionOrder$1(110), _dec3$10 = type$a(MaskType), _dec$22(_class$22 = _dec2$1r(_class$22 = (_class2$1J = (_class3$u = class Mask extends Component {
        constructor() {
          super();
          this._type = _initializer$1C && _initializer$1C();
          this._inverted = _initializer2$1f && _initializer2$1f();
          this._segments = _initializer3$U && _initializer3$U();
          this._alphaThreshold = _initializer4$N && _initializer4$N();
          this._sprite = null;
          this._graphics = null;
          this._stencilStage = 0;
        }
        get type() {
          return this._type;
        }
        set type(value) {
          if (this._type === value) {
            return;
          }
          this._type = value;
          if (this._type !== 3) {
            if (this._sprite) {
              this.node.removeComponent(Sprite);
              this._sprite._destroyImmediate();
              this._sprite = null;
            }
            this._changeRenderType();
            this._updateGraphics();
            {
              this.subComp.renderEntity.setMaskMode(this._inverted ? 2 : 1);
            }
          } else {
            if (this._graphics) {
              this._graphics.clear();
              this.node.removeComponent(Graphics);
              this._graphics._destroyImmediate();
              this._graphics = null;
            }
            this._changeRenderType();
            {
              this.subComp.renderEntity.setMaskMode(this._inverted ? 2 : 1);
            }
          }
        }
        get inverted() {
          return this._inverted;
        }
        set inverted(value) {
          this._inverted = value;
          this.subComp.stencilStage = this.inverted ? 6 : 2;
          {
            this.subComp.renderEntity.setMaskMode(this._inverted ? 2 : 1);
          }
        }
        get segments() {
          return this._segments;
        }
        set segments(value) {
          if (this._segments === value) {
            return;
          }
          this._segments = clamp$1(value, SEGMENTS_MIN, SEGMENTS_MAX);
          this._updateGraphics();
        }
        get spriteFrame() {
          if (this._sprite) {
            return this._sprite.spriteFrame;
          }
          return null;
        }
        set spriteFrame(value) {
          if (this._sprite) {
            this._sprite.spriteFrame = value;
          } else {
            errorID(16307);
          }
        }
        get alphaThreshold() {
          return this._alphaThreshold;
        }
        set alphaThreshold(value) {
          if (this._alphaThreshold === value) {
            return;
          }
          this._alphaThreshold = value;
          if (this.type === 3 && this._sprite) {
            const mat = this._sprite.getMaterialInstance(0);
            mat.setProperty('alphaThreshold', this._alphaThreshold);
          }
        }
        get subComp() {
          return this._graphics || this._sprite;
        }
        onLoad() {
          this._changeRenderType();
          {
            if (this.subComp) {
              this.subComp.renderEntity.setMaskMode(this._inverted ? 2 : 1);
            }
          }
        }
        onEnable() {
          this._changeRenderType();
          this._updateGraphics();
          this._enableRender();
          this.node.on("anchor-changed", this._nodeStateChange, this);
          this.node.on("size-changed", this._nodeStateChange, this);
        }
        onRestore() {
          this._changeRenderType();
          this._updateGraphics();
        }
        onDisable() {
          this._disableRender();
          this.node.off("anchor-changed", this._nodeStateChange, this);
          this.node.off("size-changed", this._nodeStateChange, this);
        }
        onDestroy() {
          this._removeMaskNode();
        }
        isHit(worldPt) {
          const uiTrans = this.node._uiProps.uiTransformComp;
          const size = uiTrans.contentSize;
          const w = size.width;
          const h = size.height;
          const testPt = _vec2_temp$1;
          this.node.getWorldMatrix(_worldMatrix);
          Mat4.invert(_mat4_temp$4, _worldMatrix);
          Vec2.transformMat4(testPt, worldPt, _mat4_temp$4);
          const ap = uiTrans.anchorPoint;
          testPt.x += ap.x * w;
          testPt.y += ap.y * h;
          let result = false;
          if (this.type === 0 || this.type === 2 || this.type === 3) {
            result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
          } else if (this.type === 1) {
            const rx = w / 2;
            const ry = h / 2;
            const px = testPt.x - 0.5 * w;
            const py = testPt.y - 0.5 * h;
            result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
          }
          if (this._inverted) {
            result = !result;
          }
          return result;
        }
        _nodeStateChange(type) {
          this._updateGraphics();
        }
        _changeRenderType() {
          const isGraphics = this._type !== 3;
          if (isGraphics) {
            this._createGraphics();
          } else {
            this._createSprite();
          }
        }
        _createSprite() {
          if (!this._sprite) {
            let sprite = this._sprite = this.node.getComponent(Sprite);
            if (!sprite) {
              const node = this.node;
              sprite = this._sprite = node.addComponent(Sprite);
            }
          }
          this._sprite.stencilStage = this.inverted ? 6 : 2;
          this._sprite.updateMaterial();
        }
        _createGraphics() {
          if (!this._graphics) {
            let graphics = this._graphics = this.node.getComponent(Graphics);
            if (!graphics) {
              const node = this.node;
              graphics = this._graphics = node.addComponent(Graphics);
            }
            graphics.lineWidth = 1;
            const color = Color$1.WHITE.clone();
            color.a = 0;
            graphics.fillColor = color;
          }
          this._graphics.stencilStage = this.inverted ? 6 : 2;
        }
        _updateGraphics() {
          if (!this._graphics || this._type !== 0 && this._type !== 1) {
            return;
          }
          const uiTrans = this.node._uiProps.uiTransformComp;
          const graphics = this._graphics;
          graphics.clear();
          const size = uiTrans.contentSize;
          const width = size.width;
          const height = size.height;
          const ap = uiTrans.anchorPoint;
          const x = -width * ap.x;
          const y = -height * ap.y;
          if (this._type === 0) {
            graphics.rect(x, y, width, height);
          } else if (this._type === 1) {
            const center = new Vec3(x + width / 2, y + height / 2, 0);
            const radius = new Vec3(width / 2, height / 2, 0);
            const points = _calculateCircle(center, radius, this._segments);
            for (let i = 0; i < points.length; ++i) {
              const point = points[i];
              if (i === 0) {
                graphics.moveTo(point.x, point.y);
              } else {
                graphics.lineTo(point.x, point.y);
              }
            }
            graphics.close();
          }
          graphics.fill();
        }
        _enableRender() {
          if (this.subComp) {
            this.subComp.enabled = true;
          }
        }
        _disableRender() {
          if (this.subComp) {
            this.subComp.stencilStage = 0;
            this.subComp.updateMaterial();
            if (this.node.activeInHierarchy) {
              this.subComp.enabled = false;
            }
          }
        }
        _removeMaskNode() {
          if (this._sprite) {
            this._sprite = null;
          }
          if (this._graphics) {
            this._graphics = null;
          }
        }
        get customMaterial() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.customMaterial;
          }
          return null;
        }
        set customMaterial(val) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.customMaterial = val;
          }
        }
        get color() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.color;
          }
          return null;
        }
        set color(value) {
          warnID(9007);
          if (this.subComp && value) {
            this.subComp.color = value;
          }
        }
        markForUpdateRenderData(enable = true) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.markForUpdateRenderData(enable);
          }
        }
        requestRenderData(any) {
          warnID(9007);
        }
        destroyRenderData() {
          warnID(9007);
        }
        updateRenderer() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.updateRenderer();
          }
        }
        fillBuffers(render) {
          warnID(9007);
        }
        postUpdateAssembler(render) {
          warnID(9007);
        }
        setNodeDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setNodeDirty();
          }
        }
        setTextureDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setTextureDirty();
          }
        }
        get sharedMaterial() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.sharedMaterial;
          }
          return null;
        }
        get sharedMaterials() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.sharedMaterials;
          }
          return null;
        }
        set sharedMaterials(val) {
          warnID(9007);
          if (this.subComp && val) {
            this.subComp.sharedMaterials = val;
          }
        }
        get material() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.material;
          }
          return null;
        }
        set material(val) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.material = val;
          }
        }
        get materials() {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.materials;
          }
          return [null];
        }
        set materials(val) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.materials = val;
          }
        }
        getMaterial(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getSharedMaterial(idx);
          }
          return null;
        }
        setMaterial(material, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterial(material, index);
          }
        }
        getMaterialInstance(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getMaterialInstance(idx);
          }
          return null;
        }
        setMaterialInstance(matInst, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterialInstance(matInst, index);
          }
        }
        getRenderMaterial(index) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getRenderMaterial(index);
          }
          return null;
        }
      }, _class3$u.Type = MaskType, _class3$u), (_applyDecoratedDescriptor(_class2$1J.prototype, "type", [_dec3$10], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "type"), _class2$1J.prototype), _initializer$1C = applyDecoratedInitializer(_class2$1J.prototype, "_type", [serializable$l], function () {
        return 0;
      }), _initializer2$1f = applyDecoratedInitializer(_class2$1J.prototype, "_inverted", [serializable$l], function () {
        return false;
      }), _initializer3$U = applyDecoratedInitializer(_class2$1J.prototype, "_segments", [serializable$l], function () {
        return 64;
      }), _initializer4$N = applyDecoratedInitializer(_class2$1J.prototype, "_alphaThreshold", [serializable$l], function () {
        return 0.1;
      })), _class2$1J)) || _class$22) || _class$22); exports({ Mask: Mask, MaskComponent: Mask });
      NodeEventProcessor._maskComp = Mask;
      cclegacy.Mask = Mask;

      deprecateModuleExportedName({
        RenderComponent: {
          newName: 'UIRenderer',
          since: '1.2.0',
          removed: true
        },
        UITransformComponent: {
          newName: 'UITransform',
          since: '1.2.0',
          removed: false
        },
        CanvasComponent: {
          newName: 'Canvas',
          since: '1.2.0',
          removed: false
        }
      });

      deprecateModuleExportedName({
        UIRenderable: {
          newName: 'UIRenderer',
          since: '3.0.0',
          removed: true
        }
      });

      deprecateModuleExportedName({
        Renderable2D: {
          newName: 'UIRenderer',
          since: '3.6.0',
          removed: false
        }
      });

      var _dec$21, _class$21, _class2$1I, _initializer$1B, _initializer2$1e, _initializer3$T, _class3$t;
      let PostProcess = (_dec$21 = ccclass$H('cc.PostProcess'), _dec$21(_class$21 = disallowMultiple$1(_class$21 = (_class2$1I = (_class3$t = class PostProcess extends Component {
        constructor() {
          super();
          this.global = _initializer$1B && _initializer$1B();
          this._shadingScale = _initializer2$1e && _initializer2$1e();
          this.enableShadingScaleInEditor = _initializer3$T && _initializer3$T();
          this.settings = new Map();
        }
        get shadingScale() {
          return this._shadingScale;
        }
        set shadingScale(v) {
          this._shadingScale = v;
        }
        addSetting(setting) {
          this.settings.set(setting.constructor, setting);
        }
        removeSetting(setting) {
          this.settings.delete(setting.constructor);
        }
        getSetting(ctor) {
          return this.settings.get(ctor);
        }
        onEnable() {
          PostProcess.all.push(this);
        }
        onDisable() {
          const idx = PostProcess.all.indexOf(this);
          if (idx !== -1) {
            PostProcess.all.splice(idx, 1);
          }
        }
      }, _class3$t.all = [], _class3$t), (_initializer$1B = applyDecoratedInitializer(_class2$1I.prototype, "global", [property, serializable$l], function () {
        return true;
      }), _initializer2$1e = applyDecoratedInitializer(_class2$1I.prototype, "_shadingScale", [serializable$l], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$1I.prototype, "shadingScale", [property], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "shadingScale"), _class2$1I.prototype), _initializer3$T = applyDecoratedInitializer(_class2$1I.prototype, "enableShadingScaleInEditor", [property, serializable$l], function () {
        return false;
      })), _class2$1I)) || _class$21) || _class$21);

      var _dec$20, _dec2$1q, _dec3$$, _dec4$F, _dec5$B, _dec6$s, _dec7$l, _dec8$e, _dec9$b, _dec10$5, _class$20, _class2$1H, _initializer$1A, _initializer2$1d, _initializer3$S, _initializer4$M, _initializer5$A, _initializer6$t, _initializer7$l, _initializer8$j, _initializer9$h, _initializer10$g, _initializer11$g, _initializer12$f, _initializer13$c, _initializer14$a, _initializer15$7, _initializer16$7, _initializer17$4, _initializer18$4, _initializer19$3, _initializer20$3, _initializer21$3, _initializer22$2, _class3$s;
      const _temp_vec3_1 = new Vec3();
      const ProjectionType = Enum(CameraProjection);
      const FOVAxis = Enum(CameraFOVAxis);
      const Aperture = Enum(CameraAperture);
      const Shutter = Enum(CameraShutter);
      const ISO = Enum(CameraISO);
      const ClearFlag = Enum({
        SKYBOX: 8 | 6,
        SOLID_COLOR: 7,
        DEPTH_ONLY: 6,
        DONT_CLEAR: 0
      });
      let Camera = (_dec$20 = ccclass$H('cc.Camera'), _dec2$1q = type$a(Layers.BitMask), _dec3$$ = type$a(ClearFlag), _dec4$F = type$a(ProjectionType), _dec5$B = type$a(FOVAxis), _dec6$s = type$a(Aperture), _dec7$l = type$a(Shutter), _dec8$e = type$a(ISO), _dec9$b = type$a(RenderTexture), _dec10$5 = type$a(PostProcess), _dec$20(_class$20 = (_class2$1H = (_class3$s = class Camera extends Component {
        constructor() {
          super();
          this._projection = _initializer$1A && _initializer$1A();
          this._priority = _initializer2$1d && _initializer2$1d();
          this._fov = _initializer3$S && _initializer3$S();
          this._fovAxis = _initializer4$M && _initializer4$M();
          this._orthoHeight = _initializer5$A && _initializer5$A();
          this._near = _initializer6$t && _initializer6$t();
          this._far = _initializer7$l && _initializer7$l();
          this._color = _initializer8$j && _initializer8$j();
          this._depth = _initializer9$h && _initializer9$h();
          this._stencil = _initializer10$g && _initializer10$g();
          this._clearFlags = _initializer11$g && _initializer11$g();
          this._rect = _initializer12$f && _initializer12$f();
          this._aperture = _initializer13$c && _initializer13$c();
          this._shutter = _initializer14$a && _initializer14$a();
          this._iso = _initializer15$7 && _initializer15$7();
          this._screenScale = _initializer16$7 && _initializer16$7();
          this._visibility = _initializer17$4 && _initializer17$4();
          this._targetTexture = _initializer18$4 && _initializer18$4();
          this._postProcess = _initializer19$3 && _initializer19$3();
          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();
        }
        get camera() {
          return this._camera;
        }
        get priority() {
          return this._priority;
        }
        set priority(val) {
          this._priority = val;
          if (this._camera) {
            this._camera.priority = val;
          }
        }
        get visibility() {
          return this._visibility;
        }
        set visibility(val) {
          this._visibility = val;
          if (this._camera) {
            this._camera.visibility = val;
          }
        }
        get clearFlags() {
          return this._clearFlags;
        }
        set clearFlags(val) {
          this._clearFlags = val;
          if (this._camera) {
            this._camera.clearFlag = val;
          }
        }
        get clearColor() {
          return this._color;
        }
        set clearColor(val) {
          this._color.set(val);
          if (this._camera) {
            this._camera.clearColor = this._color;
          }
        }
        get clearDepth() {
          return this._depth;
        }
        set clearDepth(val) {
          this._depth = val;
          if (this._camera) {
            this._camera.clearDepth = val;
          }
        }
        get clearStencil() {
          return this._stencil;
        }
        set clearStencil(val) {
          this._stencil = val;
          if (this._camera) {
            this._camera.clearStencil = val;
          }
        }
        get projection() {
          return this._projection;
        }
        set projection(val) {
          this._projection = val;
          if (this._camera) {
            this._camera.projectionType = val;
          }
        }
        get fovAxis() {
          return this._fovAxis;
        }
        set fovAxis(val) {
          if (val === this._fovAxis) {
            return;
          }
          this._fovAxis = val;
          if (this._camera) {
            this._camera.fovAxis = val;
            if (val === 0) {
              this.fov = this._fov * this._camera.aspect;
            } else {
              this.fov = this._fov / this._camera.aspect;
            }
          }
        }
        get fov() {
          return this._fov;
        }
        set fov(val) {
          this._fov = val;
          if (this._camera) {
            this._camera.fov = toRadian(val);
          }
        }
        get orthoHeight() {
          return this._orthoHeight;
        }
        set orthoHeight(val) {
          this._orthoHeight = val;
          if (this._camera) {
            this._camera.orthoHeight = val;
          }
        }
        get near() {
          return this._near;
        }
        set near(val) {
          this._near = val;
          if (this._camera) {
            this._camera.nearClip = val;
          }
        }
        get far() {
          return this._far;
        }
        set far(val) {
          this._far = val;
          if (this._camera) {
            this._camera.farClip = val;
          }
        }
        get aperture() {
          return this._aperture;
        }
        set aperture(val) {
          this._aperture = val;
          if (this._camera) {
            this._camera.aperture = val;
          }
        }
        get shutter() {
          return this._shutter;
        }
        set shutter(val) {
          this._shutter = val;
          if (this._camera) {
            this._camera.shutter = val;
          }
        }
        get iso() {
          return this._iso;
        }
        set iso(val) {
          this._iso = val;
          if (this._camera) {
            this._camera.iso = val;
          }
        }
        get rect() {
          return this._rect;
        }
        set rect(val) {
          this._rect = val;
          if (this._camera) {
            this._camera.setViewportInOrientedSpace(val);
          }
        }
        get targetTexture() {
          return this._targetTexture;
        }
        set targetTexture(value) {
          if (this._targetTexture === value) {
            return;
          }
          const 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("tex-change", this);
        }
        get usePostProcess() {
          return this._usePostProcess;
        }
        set usePostProcess(v) {
          this._usePostProcess = v;
          if (this._camera) {
            this._camera.usePostProcess = v;
          }
        }
        get postProcess() {
          return this._postProcess;
        }
        set postProcess(v) {
          this._postProcess = v;
          if (this._camera) {
            this._camera.postProcess = v;
          }
        }
        get screenScale() {
          return this._screenScale;
        }
        set screenScale(val) {
          this._screenScale = val;
          if (this._camera) {
            this._camera.screenScale = val;
          }
        }
        get inEditorMode() {
          return this._inEditorMode;
        }
        set inEditorMode(value) {
          this._inEditorMode = value;
          if (this._camera) {
            const root = cclegacy.director.root;
            this._camera.changeTargetWindow(value ? root && root.mainWindow : root && root.tempWindow);
          }
        }
        get cameraType() {
          return this._cameraType;
        }
        set cameraType(val) {
          if (this._cameraType === val) {
            return;
          }
          this._cameraType = val;
          if (this.camera) {
            this.camera.cameraType = val;
          }
        }
        get trackingType() {
          return this._trackingType;
        }
        set trackingType(val) {
          if (this._trackingType === val) {
            return;
          }
          this._trackingType = val;
          if (this.camera) {
            this.camera.trackingType = val;
          }
        }
        onLoad() {
          this._createCamera();
        }
        onEnable() {
          this.node.hasChangedFlags |= 1;
          if (this._camera) {
            this._attachToScene();
          }
        }
        onDisable() {
          if (this._camera) {
            this._detachFromScene();
          }
        }
        onDestroy() {
          if (this._camera) {
            this._camera.destroy();
            this._camera = null;
          }
          if (this._targetTexture) {
            this._targetTexture.off('resize');
          }
        }
        screenPointToRay(x, y, out) {
          if (!out) {
            out = Ray.create();
          }
          if (this._camera) {
            this._camera.screenPointToRay(out, x, y);
          }
          return out;
        }
        worldToScreen(worldPos, out) {
          if (!out) {
            out = new Vec3();
          }
          if (this._camera) {
            this._camera.worldToScreen(out, worldPos);
          }
          return out;
        }
        screenToWorld(screenPos, out) {
          if (!out) {
            out = this.node.getWorldPosition();
          }
          if (this._camera) {
            this._camera.screenToWorld(out, screenPos);
          }
          return out;
        }
        convertToUINode(wpos, uiNode, out) {
          if (!out) {
            out = new Vec3();
          }
          if (!this._camera) {
            return out;
          }
          this.worldToScreen(wpos, _temp_vec3_1);
          const cmp = uiNode.getComponent('cc.UITransform');
          const view = cclegacy.view;
          const designSize = view.getVisibleSize();
          const xoffset = _temp_vec3_1.x - this._camera.width * 0.5;
          const yoffset = _temp_vec3_1.y - this._camera.height * 0.5;
          _temp_vec3_1.x = xoffset / view.getScaleX() + designSize.width * 0.5;
          _temp_vec3_1.y = yoffset / view.getScaleY() + designSize.height * 0.5;
          if (cmp) {
            cmp.convertToNodeSpaceAR(_temp_vec3_1, out);
          }
          return out;
        }
        _createCamera() {
          if (!this._camera) {
            this._camera = cclegacy.director.root.createCamera();
            this._camera.initialize({
              name: this.node.name,
              node: this.node,
              projection: this._projection,
              window: this._inEditorMode ? cclegacy.director.root && cclegacy.director.root.mainWindow : cclegacy.director.root && cclegacy.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();
        }
        _attachToScene() {
          if (!this.node.scene || !this._camera) {
            return;
          }
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
          const rs = this._getRenderScene();
          rs.addCamera(this._camera);
        }
        _detachFromScene() {
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
        }
        _checkTargetTextureEvent(old) {
          if (old) {
            old.off('resize');
          }
          if (this._targetTexture) {
            this._targetTexture.on('resize', window => {
              if (this._camera) {
                this._camera.setFixedSize(window.width, window.height);
              }
            }, this);
          }
        }
        _updateTargetTexture() {
          if (!this._camera) {
            return;
          }
          if (this._targetTexture) {
            const window = this._targetTexture.window;
            this._camera.changeTargetWindow(window);
            this._camera.setFixedSize(window.width, window.height);
          }
        }
      }, _class3$s.ProjectionType = ProjectionType, _class3$s.FOVAxis = FOVAxis, _class3$s.ClearFlag = ClearFlag, _class3$s.Aperture = Aperture, _class3$s.Shutter = Shutter, _class3$s.ISO = ISO, _class3$s.TARGET_TEXTURE_CHANGE = "tex-change", _class3$s), (_initializer$1A = applyDecoratedInitializer(_class2$1H.prototype, "_projection", [serializable$l], function () {
        return ProjectionType.PERSPECTIVE;
      }), _initializer2$1d = applyDecoratedInitializer(_class2$1H.prototype, "_priority", [serializable$l], function () {
        return 0;
      }), _initializer3$S = applyDecoratedInitializer(_class2$1H.prototype, "_fov", [serializable$l], function () {
        return 45;
      }), _initializer4$M = applyDecoratedInitializer(_class2$1H.prototype, "_fovAxis", [serializable$l], function () {
        return FOVAxis.VERTICAL;
      }), _initializer5$A = applyDecoratedInitializer(_class2$1H.prototype, "_orthoHeight", [serializable$l], function () {
        return 10;
      }), _initializer6$t = applyDecoratedInitializer(_class2$1H.prototype, "_near", [serializable$l], function () {
        return 1;
      }), _initializer7$l = applyDecoratedInitializer(_class2$1H.prototype, "_far", [serializable$l], function () {
        return 1000;
      }), _initializer8$j = applyDecoratedInitializer(_class2$1H.prototype, "_color", [serializable$l], function () {
        return new Color$1('#333333');
      }), _initializer9$h = applyDecoratedInitializer(_class2$1H.prototype, "_depth", [serializable$l], function () {
        return 1;
      }), _initializer10$g = applyDecoratedInitializer(_class2$1H.prototype, "_stencil", [serializable$l], function () {
        return 0;
      }), _initializer11$g = applyDecoratedInitializer(_class2$1H.prototype, "_clearFlags", [serializable$l], function () {
        return ClearFlag.SOLID_COLOR;
      }), _initializer12$f = applyDecoratedInitializer(_class2$1H.prototype, "_rect", [serializable$l], function () {
        return new Rect$1(0, 0, 1, 1);
      }), _initializer13$c = applyDecoratedInitializer(_class2$1H.prototype, "_aperture", [serializable$l], function () {
        return Aperture.F16_0;
      }), _initializer14$a = applyDecoratedInitializer(_class2$1H.prototype, "_shutter", [serializable$l], function () {
        return Shutter.D125;
      }), _initializer15$7 = applyDecoratedInitializer(_class2$1H.prototype, "_iso", [serializable$l], function () {
        return ISO.ISO100;
      }), _initializer16$7 = applyDecoratedInitializer(_class2$1H.prototype, "_screenScale", [serializable$l], function () {
        return 1;
      }), _initializer17$4 = applyDecoratedInitializer(_class2$1H.prototype, "_visibility", [serializable$l], function () {
        return CAMERA_DEFAULT_MASK;
      }), _initializer18$4 = applyDecoratedInitializer(_class2$1H.prototype, "_targetTexture", [serializable$l], function () {
        return null;
      }), _initializer19$3 = applyDecoratedInitializer(_class2$1H.prototype, "_postProcess", [serializable$l], function () {
        return null;
      }), _initializer20$3 = applyDecoratedInitializer(_class2$1H.prototype, "_usePostProcess", [serializable$l], function () {
        return false;
      }), _initializer21$3 = applyDecoratedInitializer(_class2$1H.prototype, "_cameraType", [serializable$l], function () {
        return -1;
      }), _initializer22$2 = applyDecoratedInitializer(_class2$1H.prototype, "_trackingType", [serializable$l], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$1H.prototype, "visibility", [_dec2$1q], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "visibility"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "clearFlags", [_dec3$$], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "clearFlags"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "projection", [_dec4$F], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "projection"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "fovAxis", [_dec5$B], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "fovAxis"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "aperture", [_dec6$s], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "aperture"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "shutter", [_dec7$l], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "shutter"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "iso", [_dec8$e], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "iso"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "targetTexture", [_dec9$b], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "targetTexture"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "usePostProcess", [property], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "usePostProcess"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "postProcess", [_dec10$5], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "postProcess"), _class2$1H.prototype)), _class2$1H)) || _class$20); exports({ Camera: Camera, CameraComponent: Camera });
      cclegacy.Camera = Camera;

      var _dec$1$, _dec2$1p, _dec3$_, _class$1$;
      let RenderRoot2D = exports("RenderRoot2D", (_dec$1$ = ccclass$H('cc.RenderRoot2D'), _dec2$1p = executionOrder$1(100), _dec3$_ = requireComponent(UITransform), _dec$1$(_class$1$ = _dec2$1p(_class$1$ = _dec3$_(_class$1$ = disallowMultiple$1(_class$1$ = class RenderRoot2D extends Component {
        onEnable() {
          cclegacy.director.root.batcher2D.addScreen(this);
        }
        onDisable() {
          cclegacy.director.root.batcher2D.removeScreen(this);
        }
        onDestroy() {
          cclegacy.director.root.batcher2D.removeScreen(this);
        }
      }) || _class$1$) || _class$1$) || _class$1$) || _class$1$));

      var _dec$1_, _dec2$1o, _dec3$Z, _dec4$E, _class$1_, _class2$1G, _initializer$1z, _initializer2$1c;
      const _worldPos = new Vec3();
      const RenderMode = Enum({
        OVERLAY: 0,
        INTERSPERSE: 1
      });
      let Canvas = (_dec$1_ = ccclass$H('cc.Canvas'), _dec2$1o = executionOrder$1(100), _dec3$Z = type$a(Camera), _dec4$E = type$a(Camera), _dec$1_(_class$1_ = _dec2$1o(_class$1_ = disallowMultiple$1(_class$1_ = (_class2$1G = class Canvas extends RenderRoot2D {
        get renderMode() {
          return this._renderMode;
        }
        set renderMode(val) {
          this._renderMode = val;
          if (this._cameraComponent) {
            this._cameraComponent.priority = this._getViewPriority();
          }
        }
        get cameraComponent() {
          return this._cameraComponent;
        }
        set cameraComponent(value) {
          if (this._cameraComponent === value) {
            return;
          }
          this._cameraComponent = value;
          this._onResizeCamera();
        }
        get alignCanvasWithScreen() {
          return this._alignCanvasWithScreen;
        }
        set alignCanvasWithScreen(value) {
          this._alignCanvasWithScreen = value;
          this._onResizeCamera();
        }
        constructor() {
          super();
          this._cameraComponent = _initializer$1z && _initializer$1z();
          this._alignCanvasWithScreen = _initializer2$1c && _initializer2$1c();
          this._pos = new Vec3();
          this._renderMode = RenderMode.OVERLAY;
          this._thisOnCameraResized = this._onResizeCamera.bind(this);
        }
        __preload() {
          const widget = this.getComponent('cc.Widget');
          if (widget) {
            widget.updateAlignment();
          }
          {
            if (this._cameraComponent) {
              this._cameraComponent._createCamera();
              this._cameraComponent.node.on("tex-change", this._thisOnCameraResized);
            }
          }
          this._onResizeCamera();
          {
            view.on('canvas-resize', this._thisOnCameraResized, this);
            view.on('design-resolution-changed', this._thisOnCameraResized, this);
          }
        }
        onEnable() {
          super.onEnable();
          if (this._cameraComponent) {
            this._cameraComponent.node.on("tex-change", this._thisOnCameraResized);
          }
        }
        onDisable() {
          super.onDisable();
          if (this._cameraComponent) {
            this._cameraComponent.node.off("tex-change", this._thisOnCameraResized);
          }
        }
        onDestroy() {
          super.onDestroy();
          view.off('canvas-resize', this._thisOnCameraResized, this);
          view.off('design-resolution-changed', this._thisOnCameraResized, this);
        }
        _onResizeCamera() {
          if (this._cameraComponent && this._alignCanvasWithScreen) {
            if (this._cameraComponent.targetTexture) {
              this._cameraComponent.orthoHeight = visibleRect.height / 2;
            } else {
              const size = screen.windowSize;
              this._cameraComponent.orthoHeight = size.height / view.getScaleY() / 2;
            }
            this.node.getWorldPosition(_worldPos);
            this._cameraComponent.node.setWorldPosition(_worldPos.x, _worldPos.y, 1000);
          }
        }
        _getViewPriority() {
          if (this._cameraComponent) {
            var _this$cameraComponent;
            let 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;
        }
      }, (_applyDecoratedDescriptor(_class2$1G.prototype, "cameraComponent", [_dec3$Z], Object.getOwnPropertyDescriptor(_class2$1G.prototype, "cameraComponent"), _class2$1G.prototype), _initializer$1z = applyDecoratedInitializer(_class2$1G.prototype, "_cameraComponent", [_dec4$E], function () {
        return null;
      }), _initializer2$1c = applyDecoratedInitializer(_class2$1G.prototype, "_alignCanvasWithScreen", [serializable$l], function () {
        return true;
      })), _class2$1G)) || _class$1_) || _class$1_) || _class$1_); exports({ Canvas: Canvas, CanvasComponent: Canvas });
      cclegacy.Canvas = Canvas;

      var _dec$1Z, _dec2$1n, _dec3$Y, _class$1Z;
      let UIComponent = exports("UIComponent", (_dec$1Z = ccclass$H('cc.UIComponent'), _dec2$1n = requireComponent(UITransform), _dec3$Y = executionOrder$1(110), _dec$1Z(_class$1Z = _dec2$1n(_class$1Z = _dec3$Y(_class$1Z = disallowMultiple$1(_class$1Z = class UIComponent extends Component {
        constructor() {
          super();
          this._lastParent = null;
          this.stencilStage = 0;
        }
        __preload() {
          this.node._uiProps.uiComp = this;
        }
        onEnable() {}
        onDisable() {}
        onDestroy() {
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
        }
        postUpdateAssembler(render) {}
        markForUpdateRenderData(enable = true) {}
        setNodeDirty() {}
        setTextureDirty() {}
      }) || _class$1Z) || _class$1Z) || _class$1Z) || _class$1Z));

      removeProperty(UIComponent.prototype, 'UIComponent', [{
        name: '_visibility'
      }, {
        name: 'setVisibility'
      }]);
      replaceProperty(Canvas.prototype, 'Canvas.prototype', [{
        name: 'camera',
        newName: 'cameraComponent.camera',
        customGetter() {
          var _this$_cameraComponen;
          return (_this$_cameraComponen = this._cameraComponent) === null || _this$_cameraComponen === void 0 ? void 0 : _this$_cameraComponen.camera;
        }
      }, {
        name: 'clearFlag',
        newName: 'cameraComponent.clearFlags',
        customGetter() {
          return this._cameraComponent ? this._cameraComponent.clearFlags : 0;
        },
        customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.clearFlags = val;
        }
      }, {
        name: 'color',
        newName: 'cameraComponent.clearColor',
        customGetter() {
          return this._cameraComponent ? this._cameraComponent.clearColor : Color$1.BLACK;
        },
        customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.clearColor = val;
        }
      }, {
        name: 'priority',
        newName: 'cameraComponent.priority',
        customGetter() {
          return this._cameraComponent ? this._cameraComponent.priority : 0;
        },
        customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.priority = val;
        }
      }, {
        name: 'targetTexture',
        newName: 'cameraComponent.targetTexture',
        customGetter() {
          return this._cameraComponent ? this._cameraComponent.targetTexture : null;
        },
        customSetter(value) {
          if (this._cameraComponent) this._cameraComponent.targetTexture = value;
        }
      }, {
        name: 'visibility',
        newName: 'cameraComponent.visibility',
        customGetter() {
          return this._cameraComponent ? this._cameraComponent.visibility : 0;
        }
      }]);
      markAsWarning(UITransform.prototype, 'UITransform.prototype', [{
        name: 'priority',
        suggest: `Please use setSiblingIndex to change index of the current node in its parent's children array.`
      }]);
      cclegacy.UITransformComponent = UITransform;
      setClassAlias(UITransform, 'cc.UITransformComponent');
      setClassAlias(UIRenderer, 'cc.RenderComponent');
      cclegacy.CanvasComponent = Canvas;
      setClassAlias(Canvas, 'cc.CanvasComponent');
      cclegacy.internal.Renderable2D = UIRenderer;
      setClassAlias(UIRenderer, 'cc.Renderable2D');

      function rayAABB2(ray, min, max) {
        const o = ray.o;
        const d = ray.d;
        const ix = 1 / d.x;
        const iy = 1 / d.y;
        const iz = 1 / d.z;
        const t1 = (min.x - o.x) * ix;
        const t2 = (max.x - o.x) * ix;
        const t3 = (min.y - o.y) * iy;
        const t4 = (max.y - o.y) * iy;
        const t5 = (min.z - o.z) * iz;
        const t6 = (max.z - o.z) * iz;
        const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        const 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;
      }
      const raySubMesh = function () {
        const tri = Triangle.create();
        const deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: 2
        };
        let minDis = 0;
        const fillResult = (m, d, i0, i1, i2, r) => {
          if (m === 1) {
            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
            });
          }
        };
        const narrowphase = (vb, ib, pm, ray, opt) => {
          if (pm === 7) {
            const cnt = ib.length;
            for (let j = 0; j < cnt; j += 3) {
              const i0 = ib[j] * 3;
              const i1 = ib[j + 1] * 3;
              const 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]);
              const 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 === 2) return dist;
            }
          } else if (pm === 8) {
            const cnt = ib.length - 2;
            let rev = 0;
            for (let j = 0; j < cnt; j += 1) {
              const i0 = ib[j - rev] * 3;
              const i1 = ib[j + rev + 1] * 3;
              const 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]);
              rev = ~rev;
              const 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 === 2) return dist;
            }
          } else if (pm === 9) {
            const cnt = ib.length - 1;
            const i0 = ib[0] * 3;
            Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
            for (let j = 1; j < cnt; j += 1) {
              const i1 = ib[j] * 3;
              const i2 = ib[j + 1] * 3;
              Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
              Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
              const 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 === 2) return dist;
            }
          }
          return minDis;
        };
        return function (ray, submesh, options) {
          minDis = 0;
          if (submesh.geometricInfo.positions.length === 0) return minDis;
          const opt = options === undefined ? deOpt : options;
          const min = submesh.geometricInfo.boundingBox.min;
          const max = submesh.geometricInfo.boundingBox.max;
          if (rayAABB2(ray, min, max)) {
            const pm = submesh.primitiveMode;
            const {
              positions: vb,
              indices: ib
            } = submesh.geometricInfo;
            narrowphase(vb, ib, pm, ray, opt);
          }
          return minDis;
        };
      }();
      const rayMesh = function () {
        let minDis = 0;
        const deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: 2
        };
        return function (ray, mesh, options) {
          minDis = 0;
          const opt = options === undefined ? deOpt : options;
          const length = mesh.renderingSubMeshes.length;
          const min = mesh.struct.minPosition;
          const max = mesh.struct.maxPosition;
          if (min && max && !rayAABB2(ray, min, max)) return minDis;
          for (let i = 0; i < length; i++) {
            const sm = mesh.renderingSubMeshes[i];
            const dis = raySubMesh(ray, sm, opt);
            if (dis) {
              if (opt.mode === 1) {
                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 === 2) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === 1) {
            if (opt.result) {
              opt.result[0].distance = minDis;
              opt.result.length = 1;
            }
            if (opt.subIndices) opt.subIndices.length = 1;
          }
          return minDis;
        };
      }();
      const rayModel = function () {
        let minDis = 0;
        const deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: 2
        };
        const modelRay = new Ray();
        const m4 = new Mat4();
        return function (r, model, options) {
          minDis = 0;
          const opt = options === undefined ? deOpt : options;
          const 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);
          }
          const subModels = model.subModels;
          for (let i = 0; i < subModels.length; i++) {
            const subMesh = subModels[i].subMesh;
            const dis = raySubMesh(modelRay, subMesh, opt);
            if (dis) {
              if (opt.mode === 1) {
                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 === 2) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === 1) {
            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$1Y, _class$1Y, _class2$1F, _initializer$1y;
      getPhaseID('specular-pass');
      let ModelRenderer = (_dec$1Y = ccclass$H('cc.ModelRenderer'), _dec$1Y(_class$1Y = (_class2$1F = class ModelRenderer extends Renderer {
        constructor() {
          super();
          this._visFlags = _initializer$1y && _initializer$1y();
          this._models = [];
          this._priority = 0;
        }
        get visibility() {
          return this._visFlags;
        }
        set visibility(val) {
          this._visFlags = val;
          this._onVisibilityChange(val);
        }
        get priority() {
          return this._priority;
        }
        set priority(val) {
          if (val === this._priority) return;
          this._priority = val;
          this._updatePriority();
        }
        _collectModels() {
          return this._models;
        }
        onEnable() {
          this._updatePriority();
        }
        _attachToScene() {}
        _detachFromScene() {}
        _onVisibilityChange(val) {}
        _updatePriority() {
          if (this._models.length > 0) {
            for (let i = 0; i < this._models.length; i++) {
              this._models[i].priority = this._priority;
            }
          }
        }
      }, (_initializer$1y = applyDecoratedInitializer(_class2$1F.prototype, "_visFlags", [serializable$l], function () {
        return Layers.Enum.NONE;
      })), _class2$1F)) || _class$1Y); exports({ ModelRenderer: ModelRenderer, RenderableComponent: ModelRenderer });

      var _dec$1X, _dec2$1m, _class$1X, _class2$1E, _initializer$1x;
      const {
        ccclass: ccclass$F,
        serializable: serializable$j,
        type: type$8,
        visible: visible$2
      } = _decorator;
      let PrefabLink = exports("PrefabLink", (_dec$1X = ccclass$F('cc.PrefabLink'), _dec2$1m = type$8(Prefab), _dec$1X(_class$1X = (_class2$1E = class PrefabLink extends Component {
        constructor() {
          super();
          this.prefab = _initializer$1x && _initializer$1x();
        }
      }, (_initializer$1x = applyDecoratedInitializer(_class2$1E.prototype, "prefab", [_dec2$1m, serializable$j], function () {
        return null;
      })), _class2$1E)) || _class$1X));

      replaceProperty(Camera, 'Camera', [{
        name: 'CameraClearFlag',
        newName: 'ClearFlag'
      }]);
      replaceProperty(Camera.prototype, 'Camera.prototype', [{
        name: 'color',
        newName: 'clearColor'
      }, {
        name: 'depth',
        newName: 'clearDepth'
      }, {
        name: 'stencil',
        newName: 'clearStencil'
      }]);
      markAsWarning(Renderer.prototype, 'Renderer.prototype', [{
        name: 'getMaterial',
        suggest: 'please use renderer.getSharedMaterial instead.'
      }]);
      cclegacy.CameraComponent = Camera;
      setClassAlias(Camera, 'cc.CameraComponent');
      cclegacy.RenderableComponent = ModelRenderer;
      setClassAlias(ModelRenderer, 'cc.RenderableComponent');

      var _dec$1W, _dec2$1l, _dec3$X, _class$1W, _class2$1D, _initializer$1w, _initializer2$1b, _initializer3$R, _initializer4$L, _initializer5$z, _initializer6$s;
      let SpriteRenderer = exports("SpriteRenderer", (_dec$1W = ccclass$H('cc.SpriteRenderer'), _dec2$1l = executionOrder$1(100), _dec3$X = type$a(SpriteFrame), _dec$1W(_class$1W = _dec2$1l(_class$1W = (_class2$1D = class SpriteRenderer extends ModelRenderer {
        constructor() {
          super();
          this._spriteFrame = _initializer$1w && _initializer$1w();
          this._mode = _initializer2$1b && _initializer2$1b();
          this._color = _initializer3$R && _initializer3$R();
          this._flipX = _initializer4$L && _initializer4$L();
          this._flipY = _initializer5$z && _initializer5$z();
          this._size = _initializer6$s && _initializer6$s();
          this._model = null;
        }
        get spriteFrame() {
          return this._spriteFrame;
        }
        set spriteFrame(value) {
          if (this._spriteFrame === value) {
            return;
          }
          this._spriteFrame;
          this._spriteFrame = value;
          if (this._spriteFrame) {
            this._spriteFrame.ensureMeshData();
            const mesh = this._spriteFrame.mesh;
            mesh.initialize();
          }
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        }
        get model() {
          return this._model;
        }
        onLoad() {
          if (this._spriteFrame) {
            if (!this._spriteFrame.mesh) {
              this._spriteFrame.ensureMeshData();
            }
            this._spriteFrame.mesh.initialize();
          }
          this._updateModels();
        }
        onRestore() {
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        }
        onEnable() {
          super.onEnable();
          if (!this._model) {
            this._updateModels();
          }
          this._attachToScene();
        }
        onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
        }
        onDestroy() {
          if (this._model) {
            cclegacy.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
        }
        _updateModels() {
          if (!this._spriteFrame) {
            return;
          }
          const model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            const mesh = this._spriteFrame.mesh;
            this._model.createBoundingShape(mesh.struct.minPosition, mesh.struct.maxPosition);
            this._updateModelParams();
            this._onUpdateLocalDescriptorSet();
          }
        }
        _createModel() {
          const model = this._model = cclegacy.director.root.createModel(Model);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(this._model);
        }
        _updateModelParams() {
          if (!this._spriteFrame || !this._model) {
            return;
          }
          this._spriteFrame.ensureMeshData();
          const mesh = this._spriteFrame.mesh;
          this.node.hasChangedFlags |= 1;
          this._model.transform.hasChangedFlags |= 1;
          const renderingMesh = mesh ? mesh.renderingSubMeshes : null;
          if (renderingMesh) {
            const meshCount = renderingMesh.length;
            for (let i = 0; i < meshCount; ++i) {
              let material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              const subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        }
        _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        }
        _onMaterialModified(idx, material) {
          super._onMaterialModified(idx, material);
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
        }
        _onRebuildPSO(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._model.setSubModelMaterial(idx, material);
          this._onUpdateLocalDescriptorSet();
        }
        _onUpdateLocalDescriptorSet() {
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          const texture = this._spriteFrame.getGFXTexture();
          const sampler = this._spriteFrame.getGFXSampler();
          const subModels = this._model.subModels;
          const binding = 12;
          for (let i = 0; i < subModels.length; i++) {
            const {
              descriptorSet
            } = subModels[i];
            descriptorSet.bindTexture(binding, texture);
            descriptorSet.bindSampler(binding, sampler);
            descriptorSet.update();
          }
        }
        _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          const renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        }
        _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        }
      }, (_applyDecoratedDescriptor(_class2$1D.prototype, "spriteFrame", [_dec3$X], Object.getOwnPropertyDescriptor(_class2$1D.prototype, "spriteFrame"), _class2$1D.prototype), _initializer$1w = applyDecoratedInitializer(_class2$1D.prototype, "_spriteFrame", [serializable$l], function () {
        return null;
      }), _initializer2$1b = applyDecoratedInitializer(_class2$1D.prototype, "_mode", [serializable$l], function () {
        return 0;
      }), _initializer3$R = applyDecoratedInitializer(_class2$1D.prototype, "_color", [serializable$l], function () {
        return Color$1.WHITE.clone();
      }), _initializer4$L = applyDecoratedInitializer(_class2$1D.prototype, "_flipX", [serializable$l], function () {
        return false;
      }), _initializer5$z = applyDecoratedInitializer(_class2$1D.prototype, "_flipY", [serializable$l], function () {
        return false;
      }), _initializer6$s = applyDecoratedInitializer(_class2$1D.prototype, "_size", [serializable$l], function () {
        return new Vec2();
      })), _class2$1D)) || _class$1W) || _class$1W));

      var _dec$1V, _dec2$1k, _dec3$W, _dec4$D, _dec5$A, _dec6$r, _dec7$k, _dec8$d, _class$1V, _class2$1C, _initializer$1v, _initializer2$1a, _initializer3$Q, _initializer4$K, _initializer5$y, _initializer6$r, _initializer7$k, _initializer8$i, _initializer9$g, _initializer10$f, _initializer11$f, _initializer12$e, _initializer13$b, _initializer14$9, _class3$r;
      const _htmlTextParser = new HtmlTextParser();
      const RichTextChildName = 'RICHTEXT_CHILD';
      const RichTextChildImageName = 'RICHTEXT_Image_CHILD';
      const _tempSize = new Vec2();
      const _tempSizeLeft = new Vec2();
      const labelPool = new Pool$1(seg => {
        if (!cclegacy.isValid(seg.node)) {
          return false;
        } else {
          const label = seg.node.getComponent(Label);
          if (label) {
            label.outlineWidth = 0;
          }
        }
        return true;
      }, 20);
      const imagePool = new Pool$1(seg => {
        return cclegacy.isValid(seg.node);
      }, 10);
      function createSegment(type) {
        return {
          node: new Node$1(type),
          comp: null,
          lineCount: 0,
          styleIndex: 0,
          imageOffset: '',
          clickParam: '',
          clickHandler: '',
          type
        };
      }
      function getSegmentByPool(type, content) {
        let seg;
        if (type === RichTextChildName) {
          seg = labelPool._get();
        } else if (type === RichTextChildImageName) {
          seg = imagePool._get();
        }
        seg = seg || createSegment(type);
        let 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 = 0;
          seg.comp.verticalAlign = 0;
          seg.comp.underlineHeight = 2;
        }
        node.setPosition(0, 0, 0);
        const 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;
      }
      let RichText = (_dec$1V = ccclass$H('cc.RichText'), _dec2$1k = executionOrder$1(110), _dec3$W = type$a(HorizontalTextAlignment), _dec4$D = type$a(VerticalTextAlignment), _dec5$A = type$a(Color$1), _dec6$r = type$a(Font), _dec7$k = type$a(CacheMode), _dec8$d = type$a(SpriteAtlas), _dec$1V(_class$1V = _dec2$1k(_class$1V = (_class2$1C = (_class3$r = class RichText extends Component {
        get string() {
          return this._string;
        }
        set string(value) {
          if (this._string === value) {
            return;
          }
          this._string = value;
          this._updateRichTextStatus();
        }
        get horizontalAlign() {
          return this._horizontalAlign;
        }
        set horizontalAlign(value) {
          if (this.horizontalAlign === value) {
            return;
          }
          this._horizontalAlign = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get verticalAlign() {
          return this._verticalAlign;
        }
        set verticalAlign(value) {
          if (this._verticalAlign === value) {
            return;
          }
          this._verticalAlign = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get fontSize() {
          return this._fontSize;
        }
        set fontSize(value) {
          if (this._fontSize === value) {
            return;
          }
          this._fontSize = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get fontColor() {
          return this._fontColor;
        }
        set fontColor(value) {
          if (this._fontColor === value) {
            return;
          }
          this._fontColor = value;
          this._updateTextDefaultColor();
        }
        get fontFamily() {
          return this._fontFamily;
        }
        set fontFamily(value) {
          if (this._fontFamily === value) return;
          this._fontFamily = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get font() {
          return this._font;
        }
        set font(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();
        }
        get useSystemFont() {
          return this._isSystemFontUsed;
        }
        set useSystemFont(value) {
          if (this._isSystemFontUsed === value) {
            return;
          }
          this._isSystemFontUsed = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get cacheMode() {
          return this._cacheMode;
        }
        set cacheMode(value) {
          if (this._cacheMode === value) {
            return;
          }
          this._cacheMode = value;
          this._updateRichTextStatus();
        }
        get maxWidth() {
          return this._maxWidth;
        }
        set maxWidth(value) {
          if (this._maxWidth === value) {
            return;
          }
          this._maxWidth = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get lineHeight() {
          return this._lineHeight;
        }
        set lineHeight(value) {
          if (this._lineHeight === value) {
            return;
          }
          this._lineHeight = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get imageAtlas() {
          return this._imageAtlas;
        }
        set imageAtlas(value) {
          if (this._imageAtlas === value) {
            return;
          }
          this._imageAtlas = value;
          this._layoutDirty = true;
          this._updateRichTextStatus();
        }
        get handleTouchEvent() {
          return this._handleTouchEvent;
        }
        set handleTouchEvent(value) {
          if (this._handleTouchEvent === value) {
            return;
          }
          this._handleTouchEvent = value;
          if (this.enabledInHierarchy) {
            if (this.handleTouchEvent) {
              this._addEventListeners();
            } else {
              this._removeEventListeners();
            }
          }
        }
        constructor() {
          super();
          this._lineHeight = _initializer$1v && _initializer$1v();
          this._string = _initializer2$1a && _initializer2$1a();
          this._horizontalAlign = _initializer3$Q && _initializer3$Q();
          this._verticalAlign = _initializer4$K && _initializer4$K();
          this._fontSize = _initializer5$y && _initializer5$y();
          this._fontColor = _initializer6$r && _initializer6$r();
          this._maxWidth = _initializer7$k && _initializer7$k();
          this._fontFamily = _initializer8$i && _initializer8$i();
          this._font = _initializer9$g && _initializer9$g();
          this._isSystemFontUsed = _initializer10$f && _initializer10$f();
          this._userDefinedFont = _initializer11$f && _initializer11$f();
          this._cacheMode = _initializer12$e && _initializer12$e();
          this._imageAtlas = _initializer13$b && _initializer13$b();
          this._handleTouchEvent = _initializer14$9 && _initializer14$9();
          this._textArray = [];
          this._segments = [];
          this._labelSegmentsCache = [];
          this._linesWidth = [];
          this._lineCount = 1;
          this._labelWidth = 0;
          this._labelHeight = 0;
          this._layoutDirty = true;
          this._lineOffsetX = 0;
          this._labelChildrenNum = 0;
          this._updateRichTextStatus = this._updateRichText;
        }
        onLoad() {
          this.node.on("layer-changed", this._applyLayer, this);
          this.node.on("anchor-changed", this._updateRichTextPosition, this);
        }
        onEnable() {
          if (this.handleTouchEvent) {
            this._addEventListeners();
          }
          this._updateRichText();
          this._activateChildren(true);
        }
        onDisable() {
          if (this.handleTouchEvent) {
            this._removeEventListeners();
          }
          this._activateChildren(false);
        }
        onRestore() {
          {
            return;
          }
        }
        onDestroy() {
          for (const seg of this._segments) {
            seg.node.removeFromParent();
            if (seg.type === RichTextChildName) {
              labelPool.put(seg);
            } else if (seg.type === RichTextChildImageName) {
              imagePool.put(seg);
            }
          }
          this.node.off("anchor-changed", this._updateRichTextPosition, this);
          this.node.off("layer-changed", this._applyLayer, this);
        }
        _addEventListeners() {
          this.node.on("touch-end", this._onTouchEnded, this);
        }
        _removeEventListeners() {
          this.node.off("touch-end", this._onTouchEnded, this);
        }
        _updateLabelSegmentTextAttributes() {
          this._segments.forEach(item => {
            this._applyTextAttribute(item);
          });
        }
        _createFontLabel(str) {
          return getSegmentByPool(RichTextChildName, str);
        }
        _createImage(spriteFrame) {
          return getSegmentByPool(RichTextChildImageName, spriteFrame);
        }
        _onTTFLoaded() {
          if (this._font instanceof TTFFont) {
            this._layoutDirty = true;
            this._updateRichText();
          } else {
            this._layoutDirty = true;
            this._updateRichText();
          }
        }
        splitLongStringApproximatelyIn2048(text, styleIndex) {
          const approxSize = text.length * this.fontSize;
          const partStringArr = [];
          if (approxSize <= 2048 * 0.8) {
            partStringArr.push(text);
            return partStringArr;
          }
          this._calculateSize(_tempSize, styleIndex, text);
          if (_tempSize.x < 2048) {
            partStringArr.push(text);
          } else {
            const multilineTexts = text.split('\n');
            for (let i = 0; i < multilineTexts.length; i++) {
              this._calculateSize(_tempSize, styleIndex, multilineTexts[i]);
              if (_tempSize.x < 2048) {
                partStringArr.push(multilineTexts[i]);
              } else {
                const thisPartSplitResultArr = this.splitLongStringOver2048(multilineTexts[i], styleIndex);
                partStringArr.push(...thisPartSplitResultArr);
              }
            }
          }
          return partStringArr;
        }
        splitLongStringOver2048(text, styleIndex) {
          const partStringArr = [];
          const longStr = text;
          let curStart = 0;
          let curEnd = longStr.length / 2;
          let curString = longStr.substring(curStart, curEnd);
          let leftString = longStr.substring(curEnd);
          const curStringSize = this._calculateSize(_tempSize, styleIndex, curString);
          const leftStringSize = this._calculateSize(_tempSizeLeft, styleIndex, leftString);
          let maxWidth = this._maxWidth;
          if (this._maxWidth === 0) {
            maxWidth = 2047.9;
          }
          const lineCountForOnePart = 1;
          const 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);
          }
          let leftTryTimes = 1000;
          let curWordStep = 1;
          while (leftTryTimes && curStart < text.length) {
            while (leftTryTimes && curStringSize.x < sizeForOnePart) {
              const 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) {
              const lastWordExec = getEnglishWordPartAtLast(curString);
              if (lastWordExec && lastWordExec.length > 0 && curString !== lastWordExec[0]) {
                curEnd -= lastWordExec[0].length;
                curString = longStr.substring(curStart, curEnd);
              }
            }
            partStringArr.push(curString);
            const 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;
        }
        _measureText(styleIndex, string) {
          const func = s => {
            const width = this._calculateSize(_tempSize, styleIndex, s).x;
            return width;
          };
          if (string) {
            return func(string);
          } else {
            return func;
          }
        }
        _calculateSize(out, styleIndex, s) {
          let 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);
          const size = label.node._uiProps.uiTransformComp.contentSize;
          Vec2.set(out, size.x, size.y);
          return out;
        }
        _onTouchEnded(event) {
          const components = this.node.getComponents(Component);
          for (const seg of this._segments) {
            const clickHandler = seg.clickHandler;
            const clickParam = seg.clickParam;
            if (clickHandler && this._containsTouchLocation(seg, event.touch.getUILocation())) {
              components.forEach(component => {
                const func = component[clickHandler];
                if (component.enabledInHierarchy && func) {
                  func.call(component, event, clickParam);
                }
              });
              event.propagationStopped = true;
            }
          }
        }
        _containsTouchLocation(label, point) {
          const comp = label.node.getComponent(UITransform);
          if (!comp) {
            return false;
          }
          const myRect = comp.getBoundingBoxToWorld();
          return myRect.contains(point);
        }
        _resetState() {
          const children = this.node.children;
          for (let i = children.length - 1; i >= 0; i--) {
            const child = children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              {
                assert(child.parent === this.node);
              }
              child.parent = null;
              const 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;
        }
        _activateChildren(active) {
          for (let i = this.node.children.length - 1; i >= 0; i--) {
            const child = this.node.children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              child.active = active;
            }
          }
        }
        _addLabelSegment(stringToken, styleIndex) {
          let labelSegment;
          if (this._labelSegmentsCache.length === 0) {
            labelSegment = this._createFontLabel(stringToken);
          } else {
            labelSegment = this._labelSegmentsCache.pop();
            const label = labelSegment.node.getComponent(Label);
            if (label) {
              label.string = stringToken;
            }
          }
          const 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;
        }
        _updateRichTextWithMaxWidth(labelString, labelWidth, styleIndex) {
          let fragmentWidth = labelWidth;
          let labelSegment;
          if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this._maxWidth) {
            let checkStartIndex = 0;
            while (this._lineOffsetX <= this._maxWidth) {
              const checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length);
              const checkString = labelString.substr(checkStartIndex, checkEndIndex);
              const checkStringWidth = this._measureText(styleIndex, checkString);
              if (this._lineOffsetX + checkStringWidth <= this._maxWidth) {
                this._lineOffsetX += checkStringWidth;
                checkStartIndex += checkEndIndex;
              } else {
                if (checkStartIndex > 0) {
                  const 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) {
            const fragments = fragmentText(labelString, fragmentWidth, this._maxWidth, this._measureText(styleIndex));
            for (let k = 0; k < fragments.length; ++k) {
              const splitString = fragments[k];
              labelSegment = this._addLabelSegment(splitString, styleIndex);
              const 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);
          }
        }
        _isLastComponentCR(stringToken) {
          return stringToken.length - 1 === stringToken.lastIndexOf('\n');
        }
        _updateLineInfo() {
          this._linesWidth.push(this._lineOffsetX);
          this._lineOffsetX = 0;
          this._lineCount++;
        }
        _needsUpdateTextLayout(newTextArray) {
          if (this._layoutDirty || !this._textArray || !newTextArray) {
            return true;
          }
          if (this._textArray.length !== newTextArray.length) {
            return true;
          }
          for (let i = 0; i < this._textArray.length; i++) {
            const oldItem = this._textArray[i];
            const newItem = newTextArray[i];
            if (oldItem.text !== newItem.text) {
              return true;
            } else {
              const oldStyle = oldItem.style;
              const 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;
        }
        _addRichTextImageElement(richTextElement) {
          if (!richTextElement.style) {
            return;
          }
          const style = richTextElement.style;
          const spriteFrameName = style.src;
          const spriteFrame = this._imageAtlas && spriteFrameName && this._imageAtlas.getSpriteFrame(spriteFrameName);
          if (!spriteFrame) {
            warnID(4400);
          } else {
            const 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);
            const spriteRect = spriteFrame.rect.clone();
            let scaleFactor = 1;
            let spriteWidth = spriteRect.width;
            let spriteHeight = spriteRect.height;
            const expectWidth = style.imageWidth || 0;
            const 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 = '';
            const event = style.event;
            if (event) {
              segment.clickHandler = event.click;
              segment.clickParam = event.param;
            }
          }
        }
        _updateTextDefaultColor() {
          for (let i = 0; i < this._segments.length; ++i) {
            var _this$_textArray$segm, _this$_textArray$segm2;
            const segment = this._segments[i];
            const 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;
          }
        }
        _updateRichText() {
          if (!this.enabledInHierarchy) {
            return;
          }
          const newTextArray = _htmlTextParser.parse(this._string);
          if (!this._needsUpdateTextLayout(newTextArray)) {
            this._textArray = newTextArray.slice();
            this._updateLabelSegmentTextAttributes();
            return;
          }
          this._textArray = newTextArray.slice();
          this._resetState();
          let lastEmptyLine = false;
          let label;
          for (let i = 0; i < this._textArray.length; ++i) {
            const richTextElement = this._textArray[i];
            let 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;
              }
            }
            const splitArr = this.splitLongStringApproximatelyIn2048(text, i);
            text = splitArr.join('\n');
            const multilineTexts = text.split('\n');
            for (let j = 0; j < multilineTexts.length; ++j) {
              const 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) {
                const 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;
        }
        _getFirstWordLen(text, startIndex, textLen) {
          let character = getSymbolAt(text, startIndex);
          if (isUnicodeCJK(character) || isUnicodeSpace(character)) {
            return 1;
          }
          let len = 1;
          for (let index = startIndex + 1; index < textLen; ++index) {
            character = getSymbolAt(text, index);
            if (isUnicodeSpace(character) || isUnicodeCJK(character)) {
              break;
            }
            len++;
          }
          return len;
        }
        _updateRichTextPosition() {
          let nextTokenX = 0;
          let nextLineIndex = 1;
          const totalLineCount = this._lineCount;
          const trans = this.node._uiProps.uiTransformComp;
          const anchorX = trans.anchorX;
          const anchorY = trans.anchorY;
          for (let i = 0; i < this._segments.length; ++i) {
            const segment = this._segments[i];
            const lineCount = segment.lineCount;
            if (lineCount > nextLineIndex) {
              nextTokenX = 0;
              nextLineIndex = lineCount;
            }
            let lineOffsetX = this._labelWidth * (this._horizontalAlign * 0.5 - anchorX);
            switch (this._horizontalAlign) {
              case 0:
                break;
              case 1:
                lineOffsetX -= this._linesWidth[lineCount - 1] / 2;
                break;
              case 2:
                lineOffsetX -= this._linesWidth[lineCount - 1];
                break;
            }
            const 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;
            }
            const sprite = segment.node.getComponent(Sprite);
            if (sprite) {
              const position = segment.node.position.clone();
              const lineHeightSet = this._lineHeight;
              const 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) {
                const offsets = segment.imageOffset.split(',');
                if (offsets.length === 1 && offsets[0]) {
                  const offsetY = parseFloat(offsets[0]);
                  if (Number.isInteger(offsetY)) position.y += offsetY;
                } else if (offsets.length === 2) {
                  const offsetX = parseFloat(offsets[0]);
                  const offsetY = parseFloat(offsets[1]);
                  if (Number.isInteger(offsetX)) position.x += offsetX;
                  if (Number.isInteger(offsetY)) position.y += offsetY;
                }
              }
              segment.node.position = position;
            }
            const label = segment.node.getComponent(Label);
            if (label && label.enableOutline) {
              const position = segment.node.position.clone();
              position.y -= label.outlineWidth;
              segment.node.position = position;
            }
          }
        }
        _convertLiteralColorValue(color) {
          const colorValue = color.toUpperCase();
          if (Color$1[colorValue]) {
            const colorUse = Color$1[colorValue];
            return colorUse;
          } else {
            const out = new Color$1();
            return out.fromHEX(color);
          }
        }
        _applyTextAttribute(labelSeg) {
          const label = labelSeg.node.getComponent(Label);
          if (!label) {
            return;
          }
          this._resetLabelState(label);
          const index = labelSeg.styleIndex;
          let 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) {
              let label = labelSeg.node.getComponent(Label);
              if (!label) {
                label = labelSeg.node.addComponent(Label);
              }
              label.enableOutline = true;
              label.outlineColor = this._convertLiteralColorValue(textStyle.outline.color);
              label.outlineWidth = textStyle.outline.width;
            }
            label.fontSize = textStyle.size || this._fontSize;
            labelSeg.clickHandler = '';
            labelSeg.clickParam = '';
            const event = textStyle.event;
            if (event) {
              labelSeg.clickHandler = event.click || '';
              labelSeg.clickParam = event.param || '';
            }
          }
          label.cacheMode = this._cacheMode;
          const 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);
        }
        _applyLayer() {
          for (const seg of this._segments) {
            seg.node.layer = this.node.layer;
          }
        }
        _resetLabelState(label) {
          label.fontSize = this._fontSize;
          label.color = this._fontColor;
          label.isBold = false;
          label.isItalic = false;
          label.isUnderline = false;
        }
      }, _class3$r.HorizontalAlign = HorizontalTextAlignment, _class3$r.VerticalAlign = VerticalTextAlignment, _class3$r), (_applyDecoratedDescriptor(_class2$1C.prototype, "horizontalAlign", [_dec3$W], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "horizontalAlign"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "verticalAlign", [_dec4$D], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "verticalAlign"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "fontColor", [_dec5$A], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "fontColor"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "font", [_dec6$r], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "font"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "cacheMode", [_dec7$k], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "cacheMode"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "imageAtlas", [_dec8$d], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "imageAtlas"), _class2$1C.prototype), _initializer$1v = applyDecoratedInitializer(_class2$1C.prototype, "_lineHeight", [serializable$l], function () {
        return 40;
      }), _initializer2$1a = applyDecoratedInitializer(_class2$1C.prototype, "_string", [serializable$l], function () {
        return '<color=#00ff00>Rich</color><color=#0fffff>Text</color>';
      }), _initializer3$Q = applyDecoratedInitializer(_class2$1C.prototype, "_horizontalAlign", [serializable$l], function () {
        return 0;
      }), _initializer4$K = applyDecoratedInitializer(_class2$1C.prototype, "_verticalAlign", [serializable$l], function () {
        return 0;
      }), _initializer5$y = applyDecoratedInitializer(_class2$1C.prototype, "_fontSize", [serializable$l], function () {
        return 40;
      }), _initializer6$r = applyDecoratedInitializer(_class2$1C.prototype, "_fontColor", [serializable$l], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$k = applyDecoratedInitializer(_class2$1C.prototype, "_maxWidth", [serializable$l], function () {
        return 0;
      }), _initializer8$i = applyDecoratedInitializer(_class2$1C.prototype, "_fontFamily", [serializable$l], function () {
        return 'Arial';
      }), _initializer9$g = applyDecoratedInitializer(_class2$1C.prototype, "_font", [serializable$l], function () {
        return null;
      }), _initializer10$f = applyDecoratedInitializer(_class2$1C.prototype, "_isSystemFontUsed", [serializable$l], function () {
        return true;
      }), _initializer11$f = applyDecoratedInitializer(_class2$1C.prototype, "_userDefinedFont", [serializable$l], function () {
        return null;
      }), _initializer12$e = applyDecoratedInitializer(_class2$1C.prototype, "_cacheMode", [serializable$l], function () {
        return 0;
      }), _initializer13$b = applyDecoratedInitializer(_class2$1C.prototype, "_imageAtlas", [serializable$l], function () {
        return null;
      }), _initializer14$9 = applyDecoratedInitializer(_class2$1C.prototype, "_handleTouchEvent", [serializable$l], function () {
        return true;
      })), _class2$1C)) || _class$1V) || _class$1V); exports({ RichText: RichText, RichTextComponent: RichText });
      cclegacy.RichText = RichText;

      var _dec$1U, _dec2$1j, _class$1U;
      let UIMeshRenderer = (_dec$1U = ccclass$H('cc.UIMeshRenderer'), _dec2$1j = executionOrder$1(110), _dec$1U(_class$1U = _dec2$1j(_class$1U = class UIMeshRenderer extends Component {
        constructor() {
          super();
          this._modelComponent = null;
          this._dirtyVersion = -1;
          this._internalId = -1;
          this.stencilStage = 0;
          this._renderData = null;
          this._renderEntity = new RenderEntity(1);
          {
            this._UIModelNativeProxy = new NativeUIModelProxy();
          }
        }
        get modelComponent() {
          return this._modelComponent;
        }
        __preload() {
          this.node._uiProps.uiComp = this;
        }
        onEnable() {
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        }
        onDisable() {
          uiRendererManager.removeRenderer(this);
          this.renderEntity.enabled = this._canRender();
        }
        onLoad() {
          if (!this.node._uiProps.uiTransformComp) {
            this.node.addComponent('cc.UITransform');
          }
          this._modelComponent = this.getComponent('cc.ModelRenderer');
          if (!this._modelComponent) {
            warnID(16378, this.node ? this.node.name : '');
            return;
          }
          {
            this._UIModelNativeProxy.attachNode(this.node);
          }
          this.renderEntity.setNode(this.node);
        }
        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;
        }
        _render(render) {
          if (this._modelComponent) {
            const models = this._modelComponent._collectModels();
            this._modelComponent._detachFromScene();
            for (let i = 0; i < models.length; i++) {
              if (models[i].enabled) {
                render.commitModel(this, models[i], this._modelComponent.material);
              }
            }
            return true;
          }
          return false;
        }
        fillBuffers(render) {
          if (this.enabled) {
            this._render(render);
          }
        }
        updateRenderer() {
          {
            this.renderEntity.enabled = this._canRender();
            if (this._modelComponent) {
              const models = this._modelComponent._collectModels();
              this._modelComponent._detachFromScene();
              this._UIModelNativeProxy.clearModels();
              this._renderEntity.clearDynamicRenderDrawInfos();
              for (let i = 0; i < models.length; i++) {
                if (models[i].enabled) {
                  this._uploadRenderData(i);
                  this._UIModelNativeProxy.updateModels(models[i]);
                }
              }
              this._UIModelNativeProxy.attachDrawInfo();
            }
          }
        }
        _uploadRenderData(index) {
          {
            const renderData = MeshRenderData.add();
            renderData.initRenderDrawInfo(this, 1);
            this._renderData = renderData;
            this._renderData.material = this._modelComponent.getMaterialInstance(index);
          }
        }
        postUpdateAssembler(render) {}
        update() {
          {
            if (this._modelComponent) {
              this.markForUpdateRenderData();
            }
          }
          this._fitUIRenderQueue();
        }
        _fitUIRenderQueue() {
          if (!this._modelComponent) {
            return;
          }
          const matNum = this._modelComponent.sharedMaterials.length;
          for (let i = 0; i < matNum; i++) {
            const material = this._modelComponent.getMaterialInstance(i);
            if (material == null) {
              continue;
            }
            const passes = material.passes;
            const passNum = passes.length;
            for (let j = 0; j < passNum; j++) {
              const pass = passes[j];
              pass.setPriority(255 - 11);
              material.recompileShaders({
                CC_FORCE_FORWARD_SHADING: true
              }, j);
            }
          }
        }
        markForUpdateRenderData(enable = true) {
          uiRendererManager.markDirtyRenderer(this);
        }
        setNodeDirty() {}
        setTextureDirty() {}
        _canRender() {
          return this.enabled && this._modelComponent !== null;
        }
        get renderEntity() {
          {
            assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
          }
          return this._renderEntity;
        }
        get renderData() {
          return this._renderData;
        }
      }) || _class$1U) || _class$1U); exports({ UIMeshRenderer: UIMeshRenderer, UIModelComponent: UIMeshRenderer });
      cclegacy.UIMeshRenderer = UIMeshRenderer;

      var _dec$1T, _dec2$1i, _dec3$V, _class$1T;
      let LabelOutline = (_dec$1T = ccclass$H('cc.LabelOutline'), _dec2$1i = executionOrder$1(110), _dec3$V = requireComponent(Label), _dec$1T(_class$1T = _dec2$1i(_class$1T = _dec3$V(_class$1T = class LabelOutline extends Component {
        get color() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          return label.outlineColor;
        }
        set color(value) {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.outlineColor = value;
        }
        get width() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          return label.outlineWidth;
        }
        set width(value) {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.outlineWidth = value;
        }
        onEnable() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableOutline = true;
        }
        onDisable() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableOutline = false;
        }
      }) || _class$1T) || _class$1T) || _class$1T); exports({ LabelOutline: LabelOutline, LabelOutlineComponent: LabelOutline });
      cclegacy.LabelOutline = LabelOutline;

      const UI_VIS_FLAG = Layers.Enum.NONE | Layers.Enum.UI_3D;
      class DrawBatch2D {
        constructor() {
          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;
        }
        get inputAssembler() {
          return this._inputAssembler;
        }
        set inputAssembler(ia) {
          this._inputAssembler = ia;
        }
        get descriptorSet() {
          return this._descriptorSet;
        }
        set descriptorSet(ds) {
          this._descriptorSet = ds;
        }
        get visFlags() {
          return this._visFlags;
        }
        set visFlags(vis) {
          this._visFlags = vis;
        }
        get passes() {
          return this._passes;
        }
        get shaders() {
          return this._shaders;
        }
        destroy(ui) {
          this._passes = [];
        }
        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;
        }
        fillPasses(mat, dss, dssHash, patches) {
          if (mat) {
            const passes = mat.passes;
            if (!passes) {
              return;
            }
            this._shaders.length = passes.length;
            for (let i = 0; i < passes.length; i++) {
              if (!this._passes[i]) {
                this._passes[i] = new Pass(cclegacy.director.root);
              }
              const mtlPass = passes[i];
              const passInUse = this._passes[i];
              mtlPass.update();
              if (!dss) {
                dss = mtlPass.depthStencilState;
                dssHash = 0;
              }
              passInUse._initPassFromTarget(mtlPass, dss, dssHash);
              this._shaders[i] = passInUse.getShaderVariant(patches);
            }
          }
        }
      }

      var _dec$1S, _dec2$1h, _class$1S, _class2$1B;
      let UIStaticBatch = (_dec$1S = ccclass$H('cc.UIStaticBatch'), _dec2$1h = executionOrder$1(110), _dec$1S(_class$1S = _dec2$1h(_class$1S = (_class2$1B = class UIStaticBatch extends UIRenderer {
        constructor() {
          super();
          this._init = false;
          this._bufferAccessor = null;
          this._dirty = true;
          this._uiDrawBatchList = [];
        }
        get color() {
          return this._color;
        }
        set color(value) {
          if (this._color === value) {
            return;
          }
          this._color.set(value);
        }
        get drawBatchList() {
          return this._uiDrawBatchList;
        }
        postUpdateAssembler(render) {}
        markAsDirty() {}
        _requireDrawBatch() {
          const batch = new DrawBatch2D();
          batch.isStatic = true;
          this._uiDrawBatchList.push(batch);
          return batch;
        }
        _clearData() {
          if (this._bufferAccessor) {
            this._bufferAccessor.reset();
            const ui = this._getBatcher();
            for (let i = 0; i < this._uiDrawBatchList.length; i++) {
              const element = this._uiDrawBatchList[i];
              element.destroy(ui);
            }
          }
          this._uiDrawBatchList.length = 0;
          this._init = false;
        }
        _getBatcher() {
          if (director.root && director.root.batcher2D) {
            return director.root.batcher2D;
          }
          warnID(9301);
          return null;
        }
      }, (_applyDecoratedDescriptor(_class2$1B.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$1B.prototype, "color"), _class2$1B.prototype)), _class2$1B)) || _class$1S) || _class$1S); exports({ UIStaticBatch: UIStaticBatch, UIStaticBatchComponent: UIStaticBatch });

      var _dec$1R, _dec2$1g, _dec3$U, _class$1R;
      let LabelShadow = exports("LabelShadow", (_dec$1R = ccclass$H('cc.LabelShadow'), _dec2$1g = executionOrder$1(110), _dec3$U = requireComponent(Label), _dec$1R(_class$1R = _dec2$1g(_class$1R = _dec3$U(_class$1R = class LabelShadow extends Component {
        get color() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          return label.shadowColor;
        }
        set color(value) {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.shadowColor = value;
        }
        get offset() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          return label.shadowOffset;
        }
        set offset(value) {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.shadowOffset = value;
        }
        get blur() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          return label.shadowBlur;
        }
        set blur(value) {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.shadowBlur = value;
        }
        onEnable() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableShadow = true;
        }
        onDisable() {
          const label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableShadow = false;
        }
      }) || _class$1R) || _class$1R) || _class$1R));

      var _dec$1Q, _dec2$1f, _class$1Q, _class2$1A, _initializer$1u;
      let UIOpacity = (_dec$1Q = ccclass$H('cc.UIOpacity'), _dec2$1f = executionOrder$1(110), _dec$1Q(_class$1Q = _dec2$1f(_class$1Q = disallowMultiple$1(_class$1Q = (_class2$1A = class UIOpacity extends Component {
        constructor() {
          super();
          this._parentOpacity = 1.0;
          this._parentOpacityResetFlag = true;
          this._opacity = _initializer$1u && _initializer$1u();
        }
        get opacity() {
          return this._opacity;
        }
        set opacity(value) {
          if (this._opacity === value) {
            return;
          }
          value = clamp$1(value, 0, 255);
          this._opacity = value;
          this.node._uiProps.localOpacity = value / 255;
          this.setEntityLocalOpacityDirtyRecursively(true);
        }
        setEntityLocalOpacityDirtyRecursively(dirty) {
          {
            UIOpacity.setEntityLocalOpacityDirtyRecursively(this.node, dirty, this._parentOpacity, false);
          }
        }
        static setEntityLocalOpacityDirtyRecursively(node, dirty, parentOpacity, stopRecursiveIfHasOpacity) {
          if (!node.isValid) {
            return;
          }
          const uiOp = node.getComponent(UIOpacity);
          if (uiOp && stopRecursiveIfHasOpacity) {
            uiOp._parentOpacity = parentOpacity;
            return;
          }
          let render = node._uiProps.uiComp;
          if (!render) {
            render = node.getComponent(UIRenderer);
          }
          if (render && render.color) {
            render.renderEntity.colorDirty = dirty;
            if (uiOp) {
              uiOp._parentOpacity = parentOpacity;
              render.renderEntity.localOpacity = parentOpacity * uiOp.opacity / 255;
            } else {
              render.renderEntity.localOpacity = parentOpacity;
            }
            render.node._uiProps.localOpacity = render.renderEntity.localOpacity;
            return;
          }
          if (uiOp) {
            uiOp._parentOpacity = parentOpacity;
            parentOpacity = parentOpacity * uiOp.opacity / 255;
          }
          const children = node.children;
          for (let i = 0, len = children.length; i < len; ++i) {
            UIOpacity.setEntityLocalOpacityDirtyRecursively(children[i], dirty || parentOpacity < 1, parentOpacity, stopRecursiveIfHasOpacity);
          }
        }
        _getParentOpacity(node) {
          if (node == null || !node.isValid) {
            return 1;
          }
          const render = node._uiProps.uiComp;
          const uiOp = node.getComponent(UIOpacity);
          if (render && render.color) {
            return 1;
          }
          if (uiOp) {
            return uiOp._parentOpacity * (uiOp._opacity / 255);
          }
          return this._getParentOpacity(node.getParent());
        }
        _parentChanged() {
          const parent = this.node.getParent();
          let opacity = 1;
          if (parent) {
            this._parentOpacity = this._getParentOpacity(parent);
            opacity = this._parentOpacity;
          } else {
            this._parentOpacityResetFlag = true;
          }
          UIOpacity.setEntityLocalOpacityDirtyRecursively(this.node, true, opacity, false);
        }
        _setEntityLocalOpacityRecursively(opacity) {
          const render = this.node._uiProps.uiComp;
          if (render && render.color) {
            render.renderEntity.colorDirty = true;
            render.renderEntity.localOpacity = opacity;
            render.node._uiProps.localOpacity = opacity;
            return;
          }
          for (const child of this.node.children) {
            UIOpacity.setEntityLocalOpacityDirtyRecursively(child, true, opacity, true);
          }
        }
        onEnable() {
          this.node.on("parent-changed", this._parentChanged, this);
          this.node._uiProps.localOpacity = this._parentOpacity * this._opacity / 255;
          if (this._parentOpacityResetFlag) {
            this._parentChanged();
            this._parentOpacityResetFlag = false;
          } else {
            this._setEntityLocalOpacityRecursively(this.node._uiProps.localOpacity);
          }
        }
        onDisable() {
          this.node.off("parent-changed", this._parentChanged, this);
          this.node._uiProps.localOpacity = 1;
          this._setEntityLocalOpacityRecursively(this.node._uiProps.localOpacity);
        }
      }, (_initializer$1u = applyDecoratedInitializer(_class2$1A.prototype, "_opacity", [serializable$l], function () {
        return 255;
      })), _class2$1A)) || _class$1Q) || _class$1Q) || _class$1Q); exports({ UIOpacity: UIOpacity, UIOpacityComponent: UIOpacity });

      cclegacy.MaskComponent = Mask;
      setClassAlias(Mask, 'cc.MaskComponent');
      cclegacy.LabelComponent = Label;
      setClassAlias(Label, 'cc.LabelComponent');
      cclegacy.LabelOutlineComponent = LabelOutline;
      setClassAlias(LabelOutline, 'cc.LabelOutlineComponent');
      cclegacy.RichTextComponent = RichText;
      setClassAlias(RichText, 'cc.RichTextComponent');
      cclegacy.SpriteComponent = Sprite;
      setClassAlias(Sprite, 'cc.SpriteComponent');
      cclegacy.UIModelComponent = UIMeshRenderer;
      setClassAlias(UIMeshRenderer, 'cc.UIModelComponent');
      cclegacy.GraphicsComponent = Graphics;
      setClassAlias(Graphics, 'cc.GraphicsComponent');
      setClassAlias(UIStaticBatch, 'cc.UIStaticBatchComponent');
      setClassAlias(UIOpacity, 'cc.UIOpacityComponent');
      replaceProperty(Mask.prototype, 'Mask', [{
        name: 'graphics',
        newName: 'subComp',
        target: Mask.prototype,
        targetName: 'Mask'
      }]);
      replaceProperty(MaskType, 'MaskType', [{
        name: 'RECT',
        newName: 'GRAPHICS_RECT',
        target: MaskType,
        targetName: 'MaskType'
      }, {
        name: 'ELLIPSE',
        newName: 'GRAPHICS_ELLIPSE',
        target: MaskType,
        targetName: 'MaskType'
      }, {
        name: 'IMAGE_STENCIL',
        newName: 'SPRITE_STENCIL',
        target: MaskType,
        targetName: 'MaskType'
      }]);
      markAsWarning(LabelOutline.prototype, 'LabelOutline', [{
        name: 'width',
        suggest: 'Please use Label.outlineWidth instead.'
      }, {
        name: 'color',
        suggest: 'Please use Label.outlineColor instead.'
      }]);
      markAsWarning(LabelShadow.prototype, 'LabelShadow', [{
        name: 'color',
        suggest: 'Please use Label.shadowColor instead.'
      }, {
        name: 'offset',
        suggest: 'Please use Label.shadowOffset instead.'
      }, {
        name: 'blur',
        suggest: 'Please use Label.shadowBlur instead.'
      }]);

      class Aim {
        constructor(i, x, y) {
          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) {
        let i = 0;
        let 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$1(last, last.next)) {
          removeNode(last);
          last = last.next;
        }
        return last;
      }
      function filterPoints(start, end = null) {
        if (!start) {
          return start;
        }
        if (!end) {
          end = start;
        }
        let p = start;
        let again = false;
        do {
          again = false;
          if (!p.steiner && (equals$1(p, p.next) || area$1(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 = 0) {
        if (!ear) {
          return;
        }
        if (!pass && size) {
          indexCurve(ear, minX, minY, size);
        }
        let stop = ear;
        let prev = null;
        let 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) {
        const a = ear.prev;
        const b = ear;
        const c = ear.next;
        if (area$1(a, b, c) >= 0) {
          return false;
        }
        let 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$1(p.prev, p, p.next) >= 0) {
            return false;
          }
          p = p.next;
        }
        return true;
      }
      function isEarHashed(ear, minX, minY, size) {
        const a = ear.prev;
        const b = ear;
        const c = ear.next;
        if (area$1(a, b, c) >= 0) {
          return false;
        }
        const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x;
        const minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y;
        const maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x;
        const maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
        const minZ = zOrder(minTX, minTY, minX, minY, size);
        const maxZ = zOrder(maxTX, maxTY, minX, minY, size);
        let 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$1(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$1(p.prev, p, p.next) >= 0) {
            return false;
          }
          p = p.prevZ;
        }
        return true;
      }
      function cureLocalIntersections(start, triangles, dim) {
        let p = start;
        do {
          const a = p.prev;
          const b = p.next.next;
          if (!equals$1(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) {
        let a = start;
        do {
          let b = a.next.next;
          while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
              let 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 indexCurve(start, minX, minY, size) {
        let 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) {
        let i = 0;
        let p = null;
        let q = null;
        let e = null;
        let tail = null;
        let numMerges = 0;
        let pSize = 0;
        let qSize = 0;
        let 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 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$1(p, q, r) {
        return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
      }
      function equals$1(p1, p2) {
        return p1.x === p2.x && p1.y === p2.y;
      }
      function intersects(p1, q1, p2, q2) {
        if (equals$1(p1, q1) && equals$1(p2, q2) || equals$1(p1, q2) && equals$1(p2, q1)) {
          return true;
        }
        return area$1(p1, q1, p2) > 0 !== area$1(p1, q1, q2) > 0 && area$1(p2, q2, p1) > 0 !== area$1(p2, q2, q1) > 0;
      }
      function intersectsPolygon(a, b) {
        let 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$1(a.prev, a, a.next) < 0 ? area$1(a, b, a.next) >= 0 && area$1(a, a.prev, b) >= 0 : area$1(a, b, a.prev) < 0 || area$1(a, a.next, b) < 0;
      }
      function middleInside(a, b) {
        let p = a;
        let inside = false;
        const px = (a.x + b.x) / 2;
        const 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) {
        const a2 = new Aim(a.i, a.x, a.y);
        const b2 = new Aim(b.i, b.x, b.y);
        const an = a.next;
        const 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) {
        const 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) {
        let sum = 0;
        for (let 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;
        const outerLen = datas.length;
        let outerNode = linkedList(datas, 0, outerLen, dim, true);
        const triangles = [];
        if (!outerNode) {
          return triangles;
        }
        let minX = 0;
        let minY = 0;
        let maxX = 0;
        let maxY = 0;
        let x = 0;
        let y = 0;
        let size = 0;
        if (datas.length > 80 * dim) {
          minX = maxX = datas[0];
          minY = maxY = datas[1];
          for (let 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;
      }

      const MAX_VERTEX = 65535;
      const MAX_INDICES = MAX_VERTEX * 2;
      const PI = Math.PI;
      const min = Math.min;
      const max = Math.max;
      const ceil = Math.ceil;
      const acos = Math.acos;
      const cos = Math.cos;
      const sin = Math.sin;
      const atan2 = Math.atan2;
      const attrBytes = 8;
      let _renderData$1 = null;
      let _impl = null;
      const _curColor = new Color$1();
      const vec3_temps$1 = [];
      for (let i = 0; i < 4; i++) {
        vec3_temps$1.push(new Vec3());
      }
      function curveDivs(r, arc, tol) {
        const 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;
      }
      const graphicsAssembler = {
        useModel: true,
        updateRenderData(graphics) {
          {
            if (graphics.renderData) {
              graphics.renderData.material = graphics.getMaterialInstance(0);
            }
          }
        },
        fillBuffers(graphics, renderer) {},
        renderIA(graphics, renderer) {},
        getRenderData(graphics, vertexCount) {
          if (!_impl) {
            return null;
          }
          const renderDataList = _impl.getRenderDataList();
          let renderData = renderDataList[_impl.dataOffset];
          if (!renderData) {
            return null;
          }
          let meshBuffer = renderData;
          const 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(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(graphics) {
          Color$1.copy(_curColor, graphics.fillColor);
          this._expandFill(graphics);
          if (graphics.impl) {
            graphics.impl.updatePathOffset = true;
          }
          this.end(graphics);
        },
        end(graphics) {
          graphics.markForUpdateRenderData();
        },
        _expandStroke(graphics) {
          const w = graphics.lineWidth * 0.5;
          const lineCap = graphics.lineCap;
          const lineJoin = graphics.lineJoin;
          const miterLimit = graphics.miterLimit;
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          const nCap = curveDivs(w, PI, _impl.tessTol);
          this._calculateJoins(_impl, w, lineJoin, miterLimit);
          const paths = _impl.paths;
          let vertexCount = 0;
          for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pointsLength = path.points.length;
            if (lineJoin === 1) {
              vertexCount += (pointsLength + path.bevel * (nCap + 2) + 1) * 2;
            } else {
              vertexCount += (pointsLength + path.bevel * 5 + 1) * 2;
            }
            if (!path.closed) {
              if (lineCap === 1) {
                vertexCount += (nCap * 2 + 2) * 2;
              } else {
                vertexCount += (3 + 3) * 2;
              }
            }
          }
          const meshBuffer = _renderData$1 = this.getRenderData(graphics, vertexCount);
          if (!meshBuffer) {
            return;
          }
          const vData = meshBuffer.vData;
          const iData = meshBuffer.iData;
          for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pts = path.points;
            const pointsLength = pts.length;
            const offset = meshBuffer.vertexStart;
            let p0;
            let p1;
            let start = 0;
            let end = 0;
            const 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) {
              const dPos = new Point$1(p1.x, p1.y);
              dPos.subtract(p0);
              dPos.normalize();
              const dx = dPos.x;
              const dy = dPos.y;
              if (lineCap === 0) {
                this._buttCapStart(p0, dx, dy, w, 0);
              } else if (lineCap === 2) {
                this._buttCapStart(p0, dx, dy, w, w);
              } else if (lineCap === 1) {
                this._roundCapStart(p0, dx, dy, w, nCap);
              }
            }
            for (let j = start; j < end; ++j) {
              if (lineJoin === 1) {
                this._roundJoin(p0, p1, w, w, nCap);
              } else if ((p1.flags & (4 | 8)) !== 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) {
              const vDataOffset = offset * attrBytes;
              this._vSet(vData[vDataOffset], vData[vDataOffset + 1], 1);
              this._vSet(vData[vDataOffset + attrBytes], vData[vDataOffset + attrBytes + 1], -1);
            } else {
              const dPos = new Point$1(p1.x, p1.y);
              dPos.subtract(p0);
              dPos.normalize();
              const dx = dPos.x;
              const dy = dPos.y;
              if (lineCap === 0) {
                this._buttCapEnd(p1, dx, dy, w, 0);
              } else if (lineCap === 2) {
                this._buttCapEnd(p1, dx, dy, w, w);
              } else if (lineCap === 1) {
                this._roundCapEnd(p1, dx, dy, w, nCap);
              }
            }
            let indicesOffset = meshBuffer.indexStart;
            for (let begin = offset + 2, over = meshBuffer.vertexStart; begin < over; begin++) {
              iData[indicesOffset++] = begin - 2;
              iData[indicesOffset++] = begin - 1;
              iData[indicesOffset++] = begin;
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData$1 = null;
          _impl = null;
        },
        _expandFill(graphics) {
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          const paths = _impl.paths;
          let vertexCount = 0;
          for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pointsLength = path.points.length;
            vertexCount += pointsLength;
          }
          const renderData = _renderData$1 = this.getRenderData(graphics, vertexCount);
          if (!renderData) {
            return;
          }
          const meshBuffer = renderData;
          const vData = meshBuffer.vData;
          const iData = meshBuffer.iData;
          for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pts = path.points;
            const pointsLength = pts.length;
            if (pointsLength === 0) {
              continue;
            }
            const vertexOffset = renderData.vertexStart;
            for (let j = 0; j < pointsLength; ++j) {
              this._vSet(pts[j].x, pts[j].y);
            }
            let indicesOffset = renderData.indexStart;
            if (path.complex) {
              const earcutData = [];
              for (let j = vertexOffset, end = renderData.vertexStart; j < end; j++) {
                let vDataOffset = j * attrBytes;
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
              }
              const newIndices = earcut(earcutData, null, 3);
              if (!newIndices || newIndices.length === 0) {
                continue;
              }
              for (let j = 0, nIndices = newIndices.length; j < nIndices; j++) {
                iData[indicesOffset++] = newIndices[j] + vertexOffset;
              }
            } else {
              const first = vertexOffset;
              for (let start = vertexOffset + 2, end = meshBuffer.vertexStart; start < end; start++) {
                iData[indicesOffset++] = first;
                iData[indicesOffset++] = start - 1;
                iData[indicesOffset++] = start;
              }
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData$1 = null;
          _impl = null;
        },
        _calculateJoins(impl, w, lineJoin, miterLimit) {
          let iw = 0.0;
          if (w > 0.0) {
            iw = 1 / w;
          }
          const paths = impl.paths;
          for (let i = impl.pathOffset, l = impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pts = path.points;
            const ptsLength = pts.length;
            let p0 = pts[ptsLength - 1];
            let p1 = pts[0];
            path.bevel = 0;
            for (let j = 0; j < ptsLength; j++) {
              let dmr2 = 0;
              let cross = 0;
              let limit = 0;
              const dlx0 = p0.dy;
              const dly0 = -p0.dx;
              const dlx1 = p1.dy;
              const 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) {
                let 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 |= 2;
              }
              limit = max(11, min(p0.len, p1.len) * iw);
              if (dmr2 * limit * limit < 1) {
                p1.flags |= 8;
              }
              if (p1.flags & 1) {
                if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === 0 || lineJoin === 1) {
                  p1.flags |= 4;
                }
              }
              if ((p1.flags & (4 | 8)) !== 0) {
                path.bevel++;
              }
              p0 = p1;
              p1 = pts[j + 1];
            }
          }
        },
        _flattenPaths(impl) {
          const paths = impl.paths;
          for (let i = impl.pathOffset, l = impl.pathLength; i < l; i++) {
            const path = paths[i];
            const pts = path.points;
            let p0 = pts[pts.length - 1];
            let p1 = pts[0];
            if (pts.length > 2 && p0.equals(p1)) {
              path.closed = true;
              pts.pop();
              p0 = pts[pts.length - 1];
            }
            for (let j = 0, size = pts.length; j < size; j++) {
              const dPos = new Point$1(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(bevel, p0, p1, w) {
          const x = p1.x;
          const y = p1.y;
          let x0 = 0;
          let y0 = 0;
          let x1 = 0;
          let 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(p, dx, dy, w, d) {
          const px = p.x - dx * d;
          const py = p.y - dy * d;
          const dlx = dy;
          const dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _buttCapEnd(p, dx, dy, w, d) {
          const px = p.x + dx * d;
          const py = p.y + dy * d;
          const dlx = dy;
          const dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _roundCapStart(p, dx, dy, w, nCap) {
          const px = p.x;
          const py = p.y;
          const dlx = dy;
          const dly = -dx;
          for (let i = 0; i < nCap; i++) {
            const a = i / (nCap - 1) * PI;
            const ax = cos(a) * w;
            const 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(p, dx, dy, w, nCap) {
          const px = p.x;
          const py = p.y;
          const dlx = dy;
          const dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
          for (let i = 0; i < nCap; i++) {
            const a = i / (nCap - 1) * PI;
            const ax = cos(a) * w;
            const ay = sin(a) * w;
            this._vSet(px, py, 0);
            this._vSet(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1);
          }
        },
        _roundJoin(p0, p1, lw, rw, nCap) {
          const dlx0 = p0.dy;
          const dly0 = -p0.dx;
          const dlx1 = p1.dy;
          const dly1 = -p1.dx;
          const p1x = p1.x;
          const p1y = p1.y;
          if ((p1.flags & 2) !== 0) {
            const out = this._chooseBevel(p1.flags & 8, p0, p1, lw);
            const lx0 = out[0];
            const ly0 = out[1];
            const lx1 = out[2];
            const ly1 = out[3];
            const a0 = atan2(-dly0, -dlx0);
            let 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);
            const n = clamp(ceil((a0 - a1) / PI) * nCap, 2, nCap);
            for (let i = 0; i < n; i++) {
              const u = i / (n - 1);
              const a = a0 + u * (a1 - a0);
              const rx = p1x + cos(a) * rw;
              const 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 {
            const out = this._chooseBevel(p1.flags & 8, p0, p1, -rw);
            const rx0 = out[0];
            const ry0 = out[1];
            const rx1 = out[2];
            const ry1 = out[3];
            const a0 = atan2(dly0, dlx0);
            let a1 = atan2(dly1, dlx1);
            if (a1 < a0) {
              a1 += PI * 2;
            }
            this._vSet(p1x + dlx0 * rw, p1y + dly0 * rw, 1);
            this._vSet(rx0, ry0, -1);
            const n = clamp(ceil((a1 - a0) / PI) * nCap, 2, nCap);
            for (let i = 0; i < n; i++) {
              const u = i / (n - 1);
              const a = a0 + u * (a1 - a0);
              const lx = p1x + cos(a) * lw;
              const ly = p1y + sin(a) * 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(p0, p1, lw, rw) {
          let rx0 = 0;
          let ry0 = 0;
          let rx1 = 0;
          let ry1 = 0;
          let lx0 = 0;
          let ly0 = 0;
          let lx1 = 0;
          let ly1 = 0;
          const dlx0 = p0.dy;
          const dly0 = -p0.dx;
          const dlx1 = p1.dy;
          const dly1 = -p1.dx;
          if (p1.flags & 2) {
            const out = this._chooseBevel(p1.flags & 8, 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 {
            const out = this._chooseBevel(p1.flags & 8, p0, p1, -rw);
            rx0 = out[0];
            ry0 = out[1];
            rx1 = out[2];
            ry1 = out[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(x, y, distance = 0) {
          if (!_renderData$1) {
            return;
          }
          const meshBuffer = _renderData$1;
          let dataOffset = meshBuffer.vertexStart * attrBytes;
          const 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++;
        }
      };

      const graphicsAssemblerManager = exports("graphicsAssembler", {
        getAssembler(sprite) {
          return graphicsAssembler;
        }
      });
      Graphics.Assembler = graphicsAssemblerManager;

      const Alignment = ['left', 'center', 'right'];
      const MAX_SIZE = 2048;
      const _BASELINE_OFFSET = getBaselineOffset();
      const _invisibleAlpha = (1 / 255).toFixed(3);
      const MAX_CALCULATION_NUM = 3;
      class LetterInfo {
        constructor() {
          this.char = '';
          this.valid = true;
          this.x = 0;
          this.y = 0;
          this.line = 0;
          this.hash = '';
        }
      }
      class TextProcessing {
        constructor() {
          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;
        }
        destroy() {
          CanvasPool.getInstance().put(this._canvasData);
          this._lettersInfo.length = 0;
        }
        processingString(isBmFont, style, layout, outputLayoutData, inputString, out) {
          if (!isBmFont) {
            let 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 {
                const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
                const 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;
          }
        }
        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);
          }
        }
        setCanvasUsed(canvas, content) {
          this._canvas = canvas;
          this._context = content;
        }
        _getStyleFontScale(fontSize, fontScale) {
          let scale = fontScale;
          if (scale * fontSize > this._maxFontSize && fontSize < this._maxFontSize) {
            scale = this._maxFontSize / fontSize;
          }
          if (scale < 1) {
            scale = 1;
          }
          return scale;
        }
        _calculateLabelFont(style, layout, outputLayoutData, inputString) {
          if (!this._context) {
            return;
          }
          style.actualFontSize = style.fontSize * this._fontScale;
          {
            style.actualFontSize = Math.floor(style.actualFontSize);
            this._fontScale = style.actualFontSize / style.fontSize;
          }
          const paragraphedStrings = inputString.split('\n');
          const _splitStrings = outputLayoutData.parsedString = paragraphedStrings;
          const _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = style.fontDesc = _fontDesc;
          switch (layout.overFlow) {
            case 0:
              {
                let canvasSizeX = 0;
                let canvasSizeY = 0;
                for (let i = 0; i < paragraphedStrings.length; ++i) {
                  const 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);
                const rawWidth = canvasSizeX;
                const 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 2:
              {
                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 1:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = outputLayoutData.nodeContentSize.height * this._fontScale;
                break;
              }
            case 3:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                const 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;
              }
          }
        }
        _getFontDesc(fontSize, fontFamily, isBold, isItalic) {
          let fontDesc = `${fontSize.toString()}px `;
          fontDesc += fontFamily;
          if (isBold) {
            fontDesc = `bold ${fontDesc}`;
          }
          if (isItalic) {
            fontDesc = `italic ${fontDesc}`;
          }
          return fontDesc;
        }
        _getLineHeight(lineHeight, fontSize, drawFontsize) {
          let nodeSpacingY = lineHeight;
          if (nodeSpacingY === 0) {
            nodeSpacingY = fontSize;
          } else {
            nodeSpacingY = nodeSpacingY * fontSize / drawFontsize;
          }
          return nodeSpacingY;
        }
        _calculateShrinkFont(paragraphedStrings, style, layout, outputLayoutData) {
          if (!this._context) return;
          let _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          const paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._context, _fontDesc);
          let i = 0;
          let totalHeight = 0;
          let maxLength = 0;
          let _fontSize = style.actualFontSize;
          if (layout.wrapping) {
            const canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
            const canvasHeightNoMargin = outputLayoutData.nodeContentSize.height * this._fontScale;
            if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
              return;
            }
            totalHeight = canvasHeightNoMargin + 1;
            const actualFontSize = style.actualFontSize + 1;
            let textFragment = [];
            let left = 0;
            let right = actualFontSize | 0;
            let 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;
              const lineHeight = this._getLineHeight(layout.lineHeight, _fontSize, style.fontSize);
              totalHeight = 0;
              for (i = 0; i < paragraphedStrings.length; ++i) {
                const 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];
              }
            }
            const scaleX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) * this._fontScale / maxLength;
            const 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;
        }
        _calculateWrapText(paragraphedStrings, style, layout, outputLayoutData) {
          if (!layout.wrapping || !this._context) return;
          let _splitStrings = [];
          const canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
          const _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          for (let i = 0; i < paragraphedStrings.length; ++i) {
            const allWidth = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
            const textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._context, _fontDesc));
            _splitStrings = _splitStrings.concat(textFragment);
          }
          outputLayoutData.parsedString = _splitStrings;
          style.fontDesc = _fontDesc;
        }
        _measureText(ctx, fontDesc) {
          return str => safeMeasureText(ctx, str, fontDesc);
        }
        _calculateParagraphLength(paragraphedStrings, ctx, fontDesc) {
          const paragraphLength = [];
          for (const para of paragraphedStrings) {
            const width = safeMeasureText(ctx, para, fontDesc);
            paragraphLength.push(width);
          }
          return paragraphLength;
        }
        _updatePaddingRect(style, outputLayoutData) {
          let top = 0;
          let bottom = 0;
          let left = 0;
          let right = 0;
          let 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) {
            const shadowWidth = style.shadowBlur + outlineWidth;
            const offsetX = style.shadowOffsetX;
            const 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) {
            const 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;
        }
        _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';
        }
        _calculateFillTextStartPosition(style, layout, outputLayoutData) {
          let labelX = 0;
          if (layout.horizontalAlign === 2) {
            labelX = outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width;
          } else if (layout.horizontalAlign === 1) {
            labelX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) / 2;
          }
          const lineHeight = this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
          const drawStartY = lineHeight * (outputLayoutData.parsedString.length - 1);
          let firstLinelabelY = style.actualFontSize * (1 - BASELINE_RATIO / 2);
          if (layout.verticalAlign !== 0) {
            let blank = drawStartY + outputLayoutData.canvasPadding.height + style.actualFontSize - outputLayoutData.canvasSize.height;
            if (layout.verticalAlign === 2) {
              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);
        }
        _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);
          const 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})`;
          const tempPos = new Vec2(outputLayoutData.startPosition.x, outputLayoutData.startPosition.y);
          const drawTextPosX = tempPos.x;
          let drawTextPosY = 0;
          this._drawTextEffect(tempPos, lineHeight, style, layout, outputLayoutData);
          for (let i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosY = tempPos.y + i * lineHeight;
            if (style.hasShadow) {
              this._setupShadow(style);
              this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            if (style.isOutlined) {
              this._setupOutline(style);
              this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            if (!style.hasShadow || style.isOutlined) {
              this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
          }
          if (style.hasShadow) {
            this._context.shadowColor = 'transparent';
          }
          this._uploadTexture(outputRenderData);
        }
        _uploadTexture(outputRenderData) {
          if (outputRenderData.texture && this._canvas) {
            let tex;
            if (outputRenderData.texture instanceof SpriteFrame) {
              tex = outputRenderData.texture.texture;
            } else {
              tex = outputRenderData.texture;
            }
            const uploadAgain = this._canvas.width !== 0 && this._canvas.height !== 0;
            if (uploadAgain) {
              const oldGfxTexture = tex.getGFXTexture();
              const oldGfxSampler = tex.getGFXSampler();
              tex.reset({
                width: this._canvas.width,
                height: this._canvas.height,
                mipmapLevel: 1
              });
              tex.uploadData(this._canvas);
              tex.setWrapMode(2, 2);
              if (outputRenderData.texture instanceof SpriteFrame) {
                outputRenderData.texture.rect = new Rect$1(0, 0, this._canvas.width, this._canvas.height);
                outputRenderData.texture._calculateUV();
              }
              if (cclegacy.director.root && cclegacy.director.root.batcher2D) {
                {
                  cclegacy.director.root.batcher2D._releaseDescriptorSetCache(oldGfxTexture, oldGfxSampler);
                }
              }
            }
          }
        }
        _drawTextEffect(startPosition, lineHeight, style, layout, outputLayoutData) {
          if (!style.hasShadow && !style.isOutlined && !style.isUnderline) return;
          const isMultiple = outputLayoutData.parsedString.length > 1 && style.hasShadow;
          const measureText = this._measureText(this._context, style.fontDesc);
          let drawTextPosX = 0;
          let drawTextPosY = 0;
          for (let i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosX = startPosition.x;
            drawTextPosY = startPosition.y + i * lineHeight;
            if (isMultiple) {
              if (style.hasShadow) {
                this._setupShadow(style);
                this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
              if (style.isOutlined) {
                this._setupOutline(style);
                this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
              if (!style.hasShadow || style.isOutlined) {
                this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
            }
            if (style.isUnderline) {
              const _drawUnderlineWidth = measureText(outputLayoutData.parsedString[i]);
              const _drawUnderlinePos = new Vec2();
              if (layout.horizontalAlign === 2) {
                _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth;
              } else if (layout.horizontalAlign === 1) {
                _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';
          }
        }
        _setupOutline(style) {
          this._context.shadowBlur = 0;
          this._context.shadowOffsetX = 0;
          this._context.shadowOffsetY = 0;
          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;
        }
        _setupShadow(style) {
          const 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;
        }
        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);
          }
        }
        updateQuatCount(outputRenderData) {
          const data = outputRenderData.vertexBuffer;
          const count = outputRenderData.quadCount;
          if (data.length !== count) {
            for (let 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;
          }
        }
        _setupBMFontOverflowMetrics(layout, outputLayoutData) {
          let newWidth = outputLayoutData.nodeContentSize.width;
          let newHeight = outputLayoutData.nodeContentSize.height;
          if (layout.overFlow === 3) {
            newHeight = 0;
          }
          if (layout.overFlow === 0) {
            newWidth = 0;
            newHeight = 0;
          }
          layout.textWidthTemp = newWidth;
          layout.textHeightTemp = newHeight;
          layout.textDimensions.width = newWidth;
          layout.textDimensions.height = newHeight;
          layout.maxLineWidth = newWidth;
        }
        _updateFontScale(style) {
          style.bmfontScale = style.actualFontSize / (style.originFontSize * this._fontScale);
        }
        _computeHorizontalKerningForText(style, layout, inputString) {
          const string = inputString;
          const stringLen = string.length;
          if (!style.fntConfig) return;
          const kerningDict = style.fntConfig.kerningDict;
          const horizontalKerning = layout.horizontalKerning;
          if (!kerningDict || kerningDict.length === 0) {
            return;
          }
          let prev = -1;
          for (let i = 0; i < stringLen; ++i) {
            const key = string.charCodeAt(i);
            const kerningAmount = kerningDict[prev << 16 | key & 0xffff] || 0;
            if (i < stringLen - 1) {
              horizontalKerning[i] = kerningAmount;
            } else {
              horizontalKerning[i] = 0;
            }
            prev = key;
          }
        }
        _alignText(style, layout, outputLayoutData, inputString) {
          this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
          if (layout.overFlow === 2) {
            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);
        }
        _parsedString(outputLayoutData, inputString) {
          let _splitStrings = [];
          let textFragment = '';
          const length = getSymbolLength(inputString);
          for (let i = 0, line = 0, l = length; i < l; ++i) {
            const 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;
        }
        _multilineTextWrap(style, layout, outputLayoutData, inputString, nextTokenFunc) {
          layout.linesWidth.length = 0;
          const _string = inputString;
          const textLen = _string.length;
          let lineIndex = 0;
          let nextTokenX = 0;
          let nextTokenY = 0;
          let longestLine = 0;
          let letterRight = 0;
          let highestY = 0;
          let lowestY = 0;
          let letterDef = null;
          const _lineSpacing = 0;
          for (let index = 0; index < textLen;) {
            let character = getSymbolAt(_string, 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;
            }
            const tokenLen = nextTokenFunc(style, layout, _string, index, textLen);
            let tokenHighestY = highestY;
            let tokenLowestY = lowestY;
            let tokenRight = letterRight;
            let nextLetterX = nextTokenX;
            let newLine = false;
            const letterPosition = new Vec2();
            for (let tmp = 0; tmp < tokenLen; ++tmp) {
              const letterIndex = index + tmp;
              character = getSymbolAt(_string, letterIndex);
              if (character === '\r') {
                this._recordPlaceholderInfo(letterIndex, character);
                continue;
              }
              letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
              if (!letterDef) {
                this._recordPlaceholderInfo(letterIndex, character);
                if (style.fntConfig != null) {
                  logID(16354, style.fntConfig.atlasName, character);
                } else {
                  logID(16355, style.fontFamily, character);
                }
                continue;
              }
              const 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;
        }
        _recordPlaceholderInfo(letterIndex, char) {
          if (letterIndex >= this._lettersInfo.length) {
            const tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          this._lettersInfo[letterIndex].char = char;
          this._lettersInfo[letterIndex].hash = `${getSymbolCodeAt(char, 0)}${shareLabelInfo.hash}`;
          this._lettersInfo[letterIndex].valid = false;
        }
        _recordLetterInfo(letterPosition, character, letterIndex, lineIndex) {
          if (letterIndex >= this._lettersInfo.length) {
            const tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          const char = getSymbolCodeAt(character, 0);
          const key = `${char}${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;
        }
        _getFirstWordLen(style, layout, text, startIndex, textLen) {
          let character = getSymbolAt(text, startIndex);
          if (isUnicodeCJK(character) || character === '\n' || isUnicodeSpace(character)) {
            return 1;
          }
          let len = 1;
          let letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
          if (!letterDef) {
            return len;
          }
          let nextLetterX = letterDef.xAdvance * style.bmfontScale + layout.spacingX;
          let letterX = 0;
          for (let index = startIndex + 1; index < textLen; ++index) {
            character = getSymbolAt(text, 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;
        }
        _computeAlignmentOffset(style, layout, outputLayoutData) {
          layout.linesOffsetX.length = 0;
          layout.letterOffsetY = 0;
          switch (layout.horizontalAlign) {
            case 0:
              for (let i = 0; i < layout.numberOfLines; ++i) {
                layout.linesOffsetX.push(0);
              }
              break;
            case 1:
              for (let i = 0, l = layout.linesWidth.length; i < l; i++) {
                layout.linesOffsetX.push((outputLayoutData.nodeContentSize.width - layout.linesWidth[i]) / 2);
              }
              break;
            case 2:
              for (let i = 0, l = layout.linesWidth.length; i < l; i++) {
                layout.linesOffsetX.push(outputLayoutData.nodeContentSize.width - layout.linesWidth[i]);
              }
              break;
          }
          layout.letterOffsetY = outputLayoutData.nodeContentSize.height;
          if (layout.verticalAlign !== 0) {
            const blank = outputLayoutData.nodeContentSize.height - layout.textDesiredHeight + layout.lineHeight * this._getFontScale(style, layout) - style.originFontSize * this._fontScale * style.bmfontScale;
            if (layout.verticalAlign === 2) {
              layout.letterOffsetY -= blank;
            } else {
              layout.letterOffsetY -= blank / 2;
            }
          }
        }
        _getFontScale(style, layout) {
          return layout.overFlow === 2 ? style.bmfontScale : 1;
        }
        _isVerticalClamp(style, layout, outputLayoutData, inputString, process) {
          if (layout.textDesiredHeight > outputLayoutData.nodeContentSize.height) {
            return true;
          } else {
            return false;
          }
        }
        _isHorizontalClamp(style, layout, outputLayoutData, inputString, process) {
          let letterClamp = false;
          const _string = inputString;
          const _length = getSymbolLength(_string);
          for (let ctr = 0, l = _length; ctr < l; ++ctr) {
            const letterInfo = process._lettersInfo[ctr];
            if (letterInfo.valid) {
              const letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(letterInfo.char, shareLabelInfo);
              if (!letterDef) {
                continue;
              }
              const px = letterInfo.x + letterDef.w * style.bmfontScale;
              const lineIndex = letterInfo.line;
              if (layout.textWidthTemp > 0) {
                if (!layout.wrapping) {
                  if (px > outputLayoutData.nodeContentSize.width) {
                    letterClamp = true;
                    break;
                  }
                } else {
                  const wordWidth = layout.linesWidth[lineIndex];
                  if (wordWidth > outputLayoutData.nodeContentSize.width && (px > outputLayoutData.nodeContentSize.width || px < 0)) {
                    letterClamp = true;
                    break;
                  }
                }
              }
            }
          }
          return letterClamp;
        }
        _isHorizontalNeedShrink(layout, outputLayoutData) {
          let wordWidth = 0;
          for (let ctr = 0, l = layout.linesWidth.length; ctr < l; ++ctr) {
            wordWidth = layout.linesWidth[ctr];
            if (wordWidth > outputLayoutData.nodeContentSize.width) return true;
          }
          return false;
        }
        _shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, lambda) {
          const fontSize = style.actualFontSize;
          let left = 0;
          let right = fontSize | 0;
          let mid = 0;
          while (left < right) {
            mid = left + right + 1 >> 1;
            const 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);
          }
        }
        _scaleFontSizeDown(style, layout, outputLayoutData, inputString, fontSize) {
          let 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);
          }
        }
        _updateQuads(style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          const texture = style.spriteFrame ? style.spriteFrame.texture : shareLabelInfo.fontAtlas.getTexture();
          const appX = outputRenderData.uiTransAnchorX * outputLayoutData.nodeContentSize.width;
          const appY = outputRenderData.uiTransAnchorY * outputLayoutData.nodeContentSize.height;
          const ret = true;
          const _length = getSymbolLength(inputString);
          for (let ctr = 0, l = _length; ctr < l; ++ctr) {
            const letterInfo = this._lettersInfo[ctr];
            if (!letterInfo.valid) {
              continue;
            }
            const letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash);
            if (!letterDef) {
              warnID(16353);
              continue;
            }
            this._tmpRect.height = letterDef.h;
            this._tmpRect.width = letterDef.w;
            this._tmpRect.x = letterDef.u;
            this._tmpRect.y = letterDef.v;
            let py = letterInfo.y + layout.letterOffsetY;
            if (layout.textHeightTemp > 0) {
              if (py > layout.tailoredTopY) {
                const 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 === 1) {
                this._tmpRect.height = py < layout.tailoredBottomY ? 0 : (py - layout.tailoredBottomY) / style.bmfontScale;
              }
            }
            const lineIndex = letterInfo.line;
            const 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 === 1) {
                  this._tmpRect.width = 0;
                }
              }
            }
            if (this._tmpRect.height > 0 && this._tmpRect.width > 0) {
              const isRotated = this._determineRect(style);
              const letterPositionX = letterInfo.x + layout.linesOffsetX[letterInfo.line];
              const offset = outputRenderData.quadCount;
              outputRenderData.quadCount += 4;
              this.updateQuatCount(outputRenderData);
              callback(style, outputLayoutData, outputRenderData, offset, texture, this._tmpRect, isRotated, letterPositionX - appX, py - appY);
            }
          }
          return ret;
        }
        _isHorizontalClamped(layout, outputLayoutData, px, lineIndex) {
          const wordWidth = layout.linesWidth[lineIndex];
          const letterOverClamp = px > outputLayoutData.nodeContentSize.width || px < 0;
          if (!layout.wrapping) {
            return letterOverClamp;
          } else {
            return wordWidth > outputLayoutData.nodeContentSize.width && letterOverClamp;
          }
        }
        _determineRect(style) {
          const _spriteFrame = style.spriteFrame;
          if (!_spriteFrame) return false;
          const isRotated = _spriteFrame.isRotated();
          const originalSize = _spriteFrame.getOriginalSize();
          const rect = _spriteFrame.getRect();
          const offset = _spriteFrame.getOffset();
          const trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
          const trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
          if (!isRotated) {
            this._tmpRect.x += rect.x - trimmedLeft;
            this._tmpRect.y += rect.y + trimmedTop;
          } else {
            const 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;
        }
      }
      TextProcessing.instance = void 0;
      TextProcessing.instance = new TextProcessing();

      const _defaultLetterAtlas = new LetterAtlas(64, 64);
      const _defaultFontAtlas = new FontAtlas(null);
      let _comp$1 = null;
      let _uiTrans = null;
      let _fntConfig = null;
      let _spriteFrame = null;
      let QUAD_INDICES$6 = null;
      const bmfontUtils = {
        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;
          const overflow = comp.overflow;
          layout.overFlow = overflow;
          layout.lineHeight = comp.lineHeight;
          outputLayoutData.nodeContentSize.width = trans.width;
          outputLayoutData.nodeContentSize.height = trans.height;
          if (overflow === 0) {
            layout.wrapping = false;
            outputLayoutData.nodeContentSize.width += shareLabelInfo.margin * 2;
            outputLayoutData.nodeContentSize.height += shareLabelInfo.margin * 2;
          } else if (overflow === 3) {
            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(comp) {
          if (!comp.renderData) {
            return;
          }
          if (_comp$1 === comp) {
            return;
          }
          if (comp.renderData.vertDirty) {
            _comp$1 = comp;
            _uiTrans = _comp$1.node._uiProps.uiTransformComp;
            const renderData = comp.renderData;
            const processing = TextProcessing.instance;
            const style = comp.textStyle;
            const layout = comp.textLayout;
            const outputLayoutData = comp.textLayoutData;
            const 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);
            outputRenderData.quadCount = 0;
            processing.generateRenderInfo(true, style, layout, outputLayoutData, outputRenderData, comp.string, this.generateVertexData);
            let isResized = false;
            if (renderData.dataLength !== outputRenderData.quadCount) {
              this.resetRenderData(comp);
              renderData.dataLength = outputRenderData.quadCount;
              renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
              isResized = true;
            }
            const datalist = renderData.data;
            for (let i = 0, l = outputRenderData.quadCount; i < l; i++) {
              datalist[i] = outputRenderData.vertexBuffer[i];
            }
            const indexCount = renderData.indexCount;
            this.createQuadIndices(indexCount);
            renderData.chunk.setIndexBuffer(QUAD_INDICES$6);
            _comp$1.actualFontSize = style.actualFontSize;
            _uiTrans.setContentSize(outputLayoutData.nodeContentSize);
            this.updateUVs(comp);
            if ((_comp$1.renderEntity.colorDirty || isResized)) {
              this.updateColor(comp);
              _comp$1.node._uiProps.colorDirty = false;
            }
            renderData.vertDirty = false;
            _comp$1 = null;
            this._resetProperties();
          }
          if (comp.spriteFrame) {
            const renderData = comp.renderData;
            renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        updateUVs(label) {
          const renderData = label.renderData;
          const vData = renderData.chunk.vb;
          const vertexCount = renderData.vertexCount;
          const dataList = renderData.data;
          let vertexOffset = 3;
          for (let i = 0; i < vertexCount; i++) {
            const vert = dataList[i];
            vData[vertexOffset] = vert.u;
            vData[vertexOffset + 1] = vert.v;
            vertexOffset += 9;
          }
        },
        updateColor(label) {
          {
            const renderData = label.renderData;
            const vertexCount = renderData.vertexCount;
            if (vertexCount === 0) return;
            const vData = renderData.chunk.vb;
            const stride = renderData.floatStride;
            let colorOffset = 5;
            const color = label.color;
            const colorR = color.r / 255;
            const colorG = color.g / 255;
            const colorB = color.b / 255;
            const colorA = color.a / 255;
            for (let i = 0; i < vertexCount; i++) {
              vData[colorOffset] = colorR;
              vData[colorOffset + 1] = colorG;
              vData[colorOffset + 2] = colorB;
              vData[colorOffset + 3] = colorA;
              colorOffset += stride;
            }
          }
        },
        resetRenderData(comp) {
          const renderData = comp.renderData;
          renderData.dataLength = 0;
          renderData.resize(0, 0);
        },
        generateVertexData(style, outputLayoutData, outputRenderData, offset, spriteFrame, rect, rotated, x, y) {
          const dataOffset = offset;
          const scale = style.bmfontScale;
          const dataList = outputRenderData.vertexBuffer;
          const texW = spriteFrame.width;
          const texH = spriteFrame.height;
          const rectWidth = rect.width;
          const rectHeight = rect.height;
          let l = 0;
          let b = 0;
          let t = 0;
          let 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(comp) {
          const fontAsset = comp.font;
          _spriteFrame = fontAsset.spriteFrame;
          _fntConfig = fontAsset.fntConfig;
          shareLabelInfo.fontAtlas = fontAsset.fontDefDictionary;
          if (!shareLabelInfo.fontAtlas) {
            if (comp.cacheMode === 2) {
              shareLabelInfo.fontAtlas = _defaultLetterAtlas;
            } else {
              shareLabelInfo.fontAtlas = _defaultFontAtlas;
            }
          }
          dynamicAtlasManager.packToDynamicAtlas(comp, _spriteFrame);
        },
        _updateLabelInfo(comp) {
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        _resetProperties() {
          _fntConfig = null;
          _spriteFrame = null;
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        createQuadIndices(indexCount) {
          if (indexCount % 6 !== 0) {
            errorID(16308);
            return;
          }
          const quadCount = indexCount / 6;
          QUAD_INDICES$6 = new Uint16Array(indexCount);
          let offset = 0;
          for (let i = 0; i < quadCount; i++) {
            QUAD_INDICES$6[offset++] = 0 + i * 4;
            QUAD_INDICES$6[offset++] = 1 + i * 4;
            QUAD_INDICES$6[offset++] = 2 + i * 4;
            QUAD_INDICES$6[offset++] = 1 + i * 4;
            QUAD_INDICES$6[offset++] = 3 + i * 4;
            QUAD_INDICES$6[offset++] = 2 + i * 4;
          }
        }
      };

      const tempColor$1 = new Color$1(255, 255, 255, 255);
      const bmfont = {
        createData(comp) {
          const renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers(comp, renderer) {
          const node = comp.node;
          tempColor$1.set(comp.color);
          tempColor$1.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor$1);
        },
        appendQuad(comp, spriteFrame, rect, rotated, x, y, scale) {
          const renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          const dataOffset = renderData.dataLength;
          renderData.dataLength += 4;
          renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
          const dataList = renderData.data;
          const texW = spriteFrame.width;
          const texH = spriteFrame.height;
          const rectWidth = rect.width;
          const rectHeight = rect.height;
          let l = 0;
          let b = 0;
          let t = 0;
          let 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);

      const _atlasWidth = 1024;
      const _atlasHeight = 1024;
      let _shareAtlas = null;
      const letterFont = mixin(bmfontUtils, {
        getAssemblerData() {
          if (!_shareAtlas) {
            _shareAtlas = new LetterAtlas(_atlasWidth, _atlasHeight);
          }
          return _shareAtlas.getTexture();
        },
        _updateFontFamily(comp) {
          shareLabelInfo.fontAtlas = _shareAtlas;
          shareLabelInfo.fontFamily = this._getFontFamily(comp);
          const isOutlined = comp.enableOutline && comp.outlineWidth > 0;
          if (isOutlined) {
            shareLabelInfo.isOutlined = true;
            shareLabelInfo.margin = comp.outlineWidth;
            shareLabelInfo.out = comp.outlineColor.clone();
            shareLabelInfo.out.a = comp.outlineColor.a * comp.color.a / 255.0;
          } else {
            shareLabelInfo.isOutlined = false;
            shareLabelInfo.margin = 0;
          }
        },
        _getFontFamily(comp) {
          let fontFamily = 'Arial';
          if (!comp.useSystemFont) {
            if (comp.font) {
              fontFamily = comp.font._nativeAsset || 'Arial';
            }
          } else {
            fontFamily = comp.fontFamily || 'Arial';
          }
          return fontFamily;
        },
        _updateLabelInfo(comp) {
          shareLabelInfo.fontDesc = this._getFontDesc();
          shareLabelInfo.color = comp.color;
          shareLabelInfo.hash = computeHash(shareLabelInfo);
        },
        _getFontDesc() {
          let fontDesc = `${shareLabelInfo.fontSize.toString()}px `;
          fontDesc += shareLabelInfo.fontFamily;
          return fontDesc;
        }
      });

      const tempColor = new Color$1(255, 255, 255, 255);
      const letter = {
        createData(comp) {
          const renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers(comp, renderer) {
          if (!comp.renderData) {
            return;
          }
          const node = comp.node;
          tempColor.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor);
        },
        updateColor(label) {
          {
            const renderData = label.renderData;
            const vertexCount = renderData.vertexCount;
            if (vertexCount === 0) return;
            const vData = renderData.chunk.vb;
            const stride = renderData.floatStride;
            let colorOffset = 5;
            for (let i = 0; i < vertexCount; i++) {
              vData[colorOffset] = 1;
              vData[colorOffset + 1] = 1;
              vData[colorOffset + 2] = 1;
              vData[colorOffset + 3] = 1;
              colorOffset += stride;
            }
          }
        }
      };
      addon(letter, letterFont);

      Label.Overflow;
      const ttfUtils = {
        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 === 0) {
            layout.wrapping = false;
          } else if (comp.overflow === 3) {
            layout.wrapping = true;
          } else {
            layout.wrapping = comp.enableWrapText;
          }
          style.isBold = comp.isBold;
          style.isItalic = comp.isItalic;
          style.isUnderline = comp.isUnderline;
          style.underlineHeight = comp.underlineHeight;
          const isOutlined = comp.enableOutline && comp.outlineWidth > 0;
          if (isOutlined) {
            style.isOutlined = true;
            style.outlineColor.set(comp.outlineColor);
            style.outlineWidth = comp.outlineWidth;
          } else {
            style.isOutlined = false;
          }
          const isShadow = comp.enableShadow && (comp.shadowBlur > 0 || !approx(comp.shadowOffset.x, 0) || !approx(comp.shadowOffset.y, 0));
          if (isShadow) {
            style.hasShadow = true;
            style.shadowColor.set(comp.shadowColor);
            style.shadowBlur = comp.shadowBlur;
            style.shadowOffsetX = comp.shadowOffset.x;
            style.shadowOffsetY = comp.shadowOffset.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() {
          const sharedLabelData = Label._canvasPool.get();
          sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1;
          return sharedLabelData;
        },
        resetAssemblerData(assemblerData) {
          if (assemblerData) {
            Label._canvasPool.put(assemblerData);
          }
        },
        updateRenderData(comp) {
          if (!comp.renderData) {
            return;
          }
          if (comp.renderData.vertDirty) {
            const trans = comp.node._uiProps.uiTransformComp;
            const processing = TextProcessing.instance;
            const style = comp.textStyle;
            const layout = comp.textLayout;
            const outputLayoutData = comp.textLayoutData;
            const 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);
            const renderData = comp.renderData;
            renderData.textureDirty = true;
            this._calDynamicAtlas(comp, outputLayoutData);
            comp.actualFontSize = style.actualFontSize;
            trans.setContentSize(outputLayoutData.nodeContentSize);
            const 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) {
            const renderData = comp.renderData;
            renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        generateVertexData(style, outputLayoutData, outputRenderData) {
          const data = outputRenderData.vertexBuffer;
          const width = outputLayoutData.nodeContentSize.width;
          const height = outputLayoutData.nodeContentSize.height;
          const appX = outputRenderData.uiTransAnchorX * width;
          const 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(comp) {},
        updateUVs(comp) {},
        _updateFontFamily(comp) {
          let _fontFamily = '';
          if (!comp.useSystemFont) {
            if (comp.font) {
              _fontFamily = comp.font._nativeAsset || 'Arial';
            } else {
              _fontFamily = 'Arial';
            }
          } else {
            _fontFamily = comp.fontFamily || 'Arial';
          }
          return _fontFamily;
        },
        _calDynamicAtlas(comp, outputLayoutData) {
          if (comp.cacheMode !== 1 || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return;
          const frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(comp, frame);
        },
        _resetDynamicAtlas(comp) {
          if (comp.cacheMode !== 1) return;
          const frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.deleteAtlasSpriteFrame(frame);
          frame._resetDynamicAtlasFrame();
        }
      };

      const WHITE = Color$1.WHITE.clone();
      const QUAD_INDICES$5 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      const ttf = {
        createData(comp) {
          const renderData = comp.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          comp.textRenderData.quadCount = 4;
          const vData = renderData.chunk.vb;
          vData[3] = vData[21] = vData[22] = vData[31] = 0;
          vData[4] = vData[12] = vData[13] = vData[30] = 1;
          let offset = 5;
          for (let i = 0; i < 4; i++) {
            Color$1.toArray(vData, WHITE, offset);
            offset += 9;
          }
          renderData.chunk.setIndexBuffer(QUAD_INDICES$5);
          return renderData;
        },
        fillBuffers(comp, renderer) {
          const renderData = comp.renderData;
          const chunk = renderData.chunk;
          const dataList = renderData.data;
          const node = comp.node;
          const vData = chunk.vb;
          const m = node.worldMatrix;
          const stride = renderData.floatStride;
          let offset = 0;
          const length = dataList.length;
          for (let i = 0; i < length; i++) {
            const curData = dataList[i];
            const x = curData.x;
            const y = curData.y;
            let 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;
          }
          const vid = chunk.vertexOffset;
          const meshBuffer = chunk.meshBuffer;
          const ib = chunk.meshBuffer.iData;
          let 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(comp) {
          const renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          const uiTrans = comp.node._uiProps.uiTransformComp;
          const width = uiTrans.width;
          const height = uiTrans.height;
          const appX = uiTrans.anchorX * width;
          const appY = uiTrans.anchorY * height;
          const 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(comp) {
          const renderData = comp.renderData;
          if (!renderData || !comp.ttfSpriteFrame) {
            return;
          }
          const vData = renderData.chunk.vb;
          const 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(comp) {}
      };
      addon(ttf, ttfUtils);

      const labelAssembler = exports("labelAssembler", {
        getAssembler(comp) {
          let assembler = ttf;
          if (comp.font instanceof BitmapFont) {
            assembler = bmfont;
          } else if (comp.cacheMode === 2) {
            assembler = letter;
          }
          return assembler;
        }
      });
      Label.Assembler = labelAssembler;

      Sprite.FillType;
      const m$2 = new Mat4();
      const QUAD_INDICES$4 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      const barFilled = {
        updateRenderData(sprite) {
          const frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          const renderData = sprite.renderData;
          if (renderData && frame) {
            const vertDirty = renderData.vertDirty;
            if (!vertDirty) {
              return;
            }
            let fillStart = sprite.fillStart;
            let 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;
            let fillEnd = fillStart + fillRange;
            fillEnd = fillEnd > 1 ? 1 : fillEnd;
            this.updateUVs(sprite, fillStart, fillEnd);
            this.updateVertexData(sprite, fillStart, fillEnd);
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateUVs(sprite, fillStart, fillEnd) {
          const spriteFrame = sprite.spriteFrame;
          const renderData = sprite.renderData;
          const vData = renderData.chunk.vb;
          const atlasWidth = spriteFrame.width;
          const atlasHeight = spriteFrame.height;
          const textureRect = spriteFrame.rect;
          let ul = 0;
          let vb = 0;
          let ur = 0;
          let vt = 0;
          let quadUV0 = 0;
          let quadUV1 = 0;
          let quadUV2 = 0;
          let quadUV3 = 0;
          let quadUV4 = 0;
          let quadUV5 = 0;
          let quadUV6 = 0;
          let 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 0:
              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 1:
              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(sprite, fillStart, fillEnd) {
          const renderData = sprite.renderData;
          const dataList = renderData.data;
          const uiTrans = sprite.node._uiProps.uiTransformComp;
          const width = uiTrans.width;
          const height = uiTrans.height;
          const appX = uiTrans.anchorX * width;
          const appY = uiTrans.anchorY * height;
          let l = -appX;
          let b = -appY;
          let r = width - appX;
          let t = height - appY;
          let progressStart = 0;
          let progressEnd = 0;
          switch (sprite.fillType) {
            case 0:
              progressStart = l + (r - l) * fillStart;
              progressEnd = l + (r - l) * fillEnd;
              l = progressStart;
              r = progressEnd;
              break;
            case 1:
              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(sprite) {
          const renderData = sprite.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          renderData.chunk.setIndexBuffer(QUAD_INDICES$4);
          const dataList = renderData.data;
          for (const data of dataList) {
            data.z = 0;
          }
          return renderData;
        },
        updateWorldVertexData(sprite, chunk) {
          const node = sprite.node;
          node.getWorldMatrix(m$2);
          const renderData = sprite.renderData;
          const stride = renderData.floatStride;
          const dataList = sprite.renderData.data;
          const vData = chunk.vb;
          let offset = 0;
          for (let i = 0; i < 4; i++) {
            const local = dataList[i];
            const x = local.x;
            const y = local.y;
            let rhw = m$2.m03 * x + m$2.m07 * y + m$2.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset] = (m$2.m00 * x + m$2.m04 * y + m$2.m12) * rhw;
            vData[offset + 1] = (m$2.m01 * x + m$2.m05 * y + m$2.m13) * rhw;
            vData[offset + 2] = (m$2.m02 * x + m$2.m06 * y + m$2.m14) * rhw;
          }
        },
        fillBuffers(sprite, renderer) {
          const renderData = sprite.renderData;
          const 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;
          const vid = chunk.vertexOffset;
          const meshBuffer = chunk.meshBuffer;
          const ib = chunk.meshBuffer.iData;
          let 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(sprite) {
          const renderData = sprite.renderData;
          const vData = renderData.chunk.vb;
          const stride = renderData.floatStride;
          let colorOffset = 5;
          const color = sprite.color;
          const colorR = color.r / 255;
          const colorG = color.g / 255;
          const colorB = color.b / 255;
          const colorA = sprite.node._uiProps.opacity;
          for (let i = 0; i < 4; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

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

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

      const tempRenderData$1 = [];
      for (let i = 0; i < 4; i++) {
        tempRenderData$1.push({
          x: 0,
          y: 0,
          z: 0,
          u: 0,
          v: 0,
          color: new Color$1()
        });
      }
      const sliced = {
        createData(sprite) {
          const 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(vertexRow, vertexCol) {
          let offset = 0;
          for (let curRow = 0; curRow < vertexRow - 1; curRow++) {
            for (let curCol = 0; curCol < vertexCol - 1; curCol++) {
              const 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(sprite) {
          const frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          const renderData = sprite.renderData;
          if (renderData && frame) {
            const vertDirty = renderData.vertDirty;
            if (vertDirty) {
              this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateVertexData(sprite) {
          const renderData = sprite.renderData;
          const dataList = renderData.data;
          const uiTrans = sprite.node._uiProps.uiTransformComp;
          const width = uiTrans.width;
          const height = uiTrans.height;
          const appX = uiTrans.anchorX * width;
          const appY = uiTrans.anchorY * height;
          const frame = sprite.spriteFrame;
          const leftWidth = frame.insetLeft;
          const rightWidth = frame.insetRight;
          const topHeight = frame.insetTop;
          const bottomHeight = frame.insetBottom;
          let sizableWidth = width - leftWidth - rightWidth;
          let sizableHeight = height - topHeight - bottomHeight;
          let xScale = width / (leftWidth + rightWidth);
          let 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 (let curRow = 0; curRow < 4; curRow++) {
            for (let curCol = 0; curCol < 4; curCol++) {
              const 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(sprite, renderer) {
          const renderData = sprite.renderData;
          const 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;
          const vid = chunk.vertexOffset;
          const meshBuffer = chunk.meshBuffer;
          const ib = chunk.meshBuffer.iData;
          let indexOffset = meshBuffer.indexOffset;
          for (let r = 0; r < 3; ++r) {
            for (let c = 0; c < 3; ++c) {
              const 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(sprite, chunk) {
          const renderData = sprite.renderData;
          const stride = renderData.floatStride;
          const dataList = renderData.data;
          const vData = chunk.vb;
          const node = sprite.node;
          const m = node.worldMatrix;
          const m00 = m.m00;
          const m01 = m.m01;
          const m02 = m.m02;
          const m03 = m.m03;
          const m04 = m.m04;
          const m05 = m.m05;
          const m06 = m.m06;
          const m07 = m.m07;
          const m12 = m.m12;
          const m13 = m.m13;
          const m14 = m.m14;
          const m15 = m.m15;
          let offset = 0;
          for (let row = 0; row < 4; ++row) {
            const rowD = dataList[row * 4];
            for (let col = 0; col < 4; ++col) {
              const colD = dataList[col];
              const x = colD.x;
              const y = rowD.y;
              let rhw = m03 * x + m07 * y + m15;
              rhw = rhw ? 1 / rhw : 1;
              offset = (row * 4 + col) * stride;
              vData[offset + 0] = (m00 * x + m04 * y + m12) * rhw;
              vData[offset + 1] = (m01 * x + m05 * y + m13) * rhw;
              vData[offset + 2] = (m02 * x + m06 * y + m14) * rhw;
            }
          }
        },
        updateUVs(sprite) {
          if (!sprite.spriteFrame) return;
          const renderData = sprite.renderData;
          const vData = renderData.chunk.vb;
          const stride = renderData.floatStride;
          const uv = sprite.spriteFrame.uvSliced;
          let uvOffset = 3;
          for (let i = 0; i < 16; i++) {
            vData[uvOffset] = uv[i].u;
            vData[uvOffset + 1] = uv[i].v;
            uvOffset += stride;
          }
        },
        updateColor(sprite) {
          const renderData = sprite.renderData;
          const vData = renderData.chunk.vb;
          const stride = renderData.floatStride;
          let colorOffset = 5;
          const color = sprite.color;
          const colorR = color.r / 255;
          const colorG = color.g / 255;
          const colorB = color.b / 255;
          const colorA = sprite.node._uiProps.opacity;
          for (let i = 0; i < 16; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

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

      Sprite.Type;
      Sprite.FillType;
      const spriteAssembler = exports("spriteAssembler", {
        getAssembler(spriteComp) {
          let util = simple$3;
          const comp = spriteComp;
          switch (comp.type) {
            case 1:
              util = sliced;
              break;
            case 2:
              util = tiled;
              break;
            case 3:
              if (comp.fillType === 2) {
                util = radialFilled;
              } else {
                util = barFilled;
              }
              break;
          }
          return util;
        }
      });
      Sprite.Assembler = spriteAssembler;

      class StencilManager {
        constructor() {
          this._maskStack = [];
          this._stencilPattern = {
            stencilTest: true,
            func: 7,
            stencilMask: 0xffff,
            writeMask: 0xffff,
            failOp: 1,
            zFailOp: 1,
            passOp: 1,
            ref: 1
          };
          this._stage = 0;
          this.stencilStateMap = new Map();
          this.stencilStateMapWithDepth = new Map();
        }
        get stage() {
          return this._stage;
        }
        set stage(val) {
          this._stage = val;
        }
        get pattern() {
          return this._stencilPattern;
        }
        pushMask(mask) {
          this._maskStack.push(mask);
        }
        clear(comp) {
          const isInverted = comp.stencilStage !== 2;
          return isInverted ? 5 : 1;
        }
        enableMask() {
          this.stage = 3;
        }
        exitMask() {
          if (this._maskStack.length === 0) {
            return;
          }
          this._maskStack.pop();
          if (this._maskStack.length === 0) {
            this.stage = 0;
          } else {
            this.stage = 3;
          }
        }
        getWriteMask() {
          return 1 << this._maskStack.length - 1;
        }
        getExitWriteMask() {
          return 1 << this._maskStack.length;
        }
        getStencilRef() {
          let result = 0;
          for (let i = 0; i < this._maskStack.length; ++i) {
            result += 0x00000001 << i;
          }
          return result;
        }
        getMaskStackSize() {
          return this._maskStack.length;
        }
        reset() {
          this._maskStack.length = 0;
          this.stage = 0;
        }
        destroy() {
          this.stencilStateMap.forEach((value, key) => {
            value.destroy();
          });
          this.stencilStateMap.clear();
        }
        getStencilStage(stage, mat) {
          let key = 0;
          let depthTest = false;
          let depthWrite = false;
          let depthFunc = 1;
          let cacheMap = this.stencilStateMap;
          if (mat && mat.passes[0]) {
            const pass = mat.passes[0];
            const dss = pass.depthStencilState;
            let depthTestValue = 0;
            let 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);
          const 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;
        }
        getStencilHash(stage) {
          return stage << 8 | this._maskStack.length;
        }
        setStateFromStage(stage) {
          const pattern = this._stencilPattern;
          if (stage === 0) {
            pattern.stencilTest = false;
            pattern.func = 7;
            pattern.failOp = 1;
            pattern.stencilMask = pattern.writeMask = 0xffff;
            pattern.ref = 1;
          } else {
            pattern.stencilTest = true;
            if (stage === 3) {
              pattern.func = 2;
              pattern.failOp = 1;
              pattern.stencilMask = pattern.ref = this.getStencilRef();
              pattern.writeMask = this.getWriteMask();
            } else if (stage === 1) {
              pattern.func = 0;
              pattern.failOp = 0;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === 5) {
              pattern.func = 0;
              pattern.failOp = 2;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === 2) {
              pattern.func = 0;
              pattern.failOp = 2;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === 6) {
              pattern.func = 0;
              pattern.failOp = 0;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            }
          }
        }
      } exports("StencilManager", StencilManager);
      StencilManager.sharedManager = null;
      StencilManager.sharedManager = new StencilManager();

      const mouseEvents = ["mouse-down", "mouse-move", "mouse-up", "mouse-wheel", "mouse-leave-window", "mouse-enter-window"];
      const touchEvents = ["touch-start", "touch-move", "touch-end", "touch-cancel"];
      class PointerEventDispatcher {
        constructor() {
          this.priority = 1;
          this._isListDirty = false;
          this._inDispatchCount = 0;
          this._pointerEventProcessorList = [];
          this._processorListToAdd = [];
          this._processorListToRemove = [];
          input$1._registerEventDispatcher(this);
          NodeEventProcessor.callbacksInvoker.on(0, this.addPointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(1, this.removePointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(2, this._markListDirty, this);
        }
        onThrowException() {
          this._inDispatchCount = 0;
        }
        dispatchEvent(event) {
          const eventType = event.type;
          if (touchEvents.includes(eventType)) {
            return this.dispatchEventTouch(event);
          } else if (mouseEvents.includes(eventType)) {
            return this.dispatchEventMouse(event);
          }
          return true;
        }
        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);
        }
        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);
        }
        dispatchEventMouse(eventMouse) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          const pointerEventProcessorList = this._pointerEventProcessorList;
          const length = pointerEventProcessorList.length;
          let dispatchToNextEventDispatcher = true;
          for (let i = 0; i < length; ++i) {
            const 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;
        }
        dispatchEventTouch(eventTouch) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          const pointerEventProcessorList = this._pointerEventProcessorList;
          const length = pointerEventProcessorList.length;
          const touch = eventTouch.touch;
          let dispatchToNextEventDispatcher = true;
          for (let i = 0; i < length; ++i) {
            const pointerEventProcessor = pointerEventProcessorList[i];
            if (pointerEventProcessor.isEnabled && pointerEventProcessor.shouldHandleEventTouch) {
              if (eventTouch.type === "touch-start") {
                if (pointerEventProcessor._handleEventTouch(eventTouch)) {
                  if (pointerEventProcessor.isEnabled) {
                    pointerEventProcessor.claimedTouchIdList.push(touch.getID());
                  } else {
                    const cancelEvent = new EventTouch([eventTouch.touch], true, "touch-cancel");
                    cancelEvent.touch = eventTouch.touch;
                    pointerEventProcessor.dispatchEvent(cancelEvent);
                    pointerEventProcessor.claimedTouchIdList.length = 0;
                  }
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              } else if (pointerEventProcessor.claimedTouchIdList.length > 0) {
                const index = pointerEventProcessor.claimedTouchIdList.indexOf(touch.getID());
                if (index !== -1) {
                  pointerEventProcessor._handleEventTouch(eventTouch);
                  if (eventTouch.type === "touch-end" || eventTouch.type === "touch-cancel") {
                    removeAt(pointerEventProcessor.claimedTouchIdList, index);
                    if (!eventTouch.preventSwallow) {
                      this._removeClaimedTouch(i + 1, touch.getID());
                    }
                  }
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              }
            }
          }
          if (--this._inDispatchCount <= 0) {
            this._updatePointerEventProcessorList();
          }
          return dispatchToNextEventDispatcher;
        }
        _removeClaimedTouch(eventProcessorIndex, touchID) {
          const pointerEventProcessorList = this._pointerEventProcessorList;
          const length = pointerEventProcessorList.length;
          for (let i = eventProcessorIndex; i < length; ++i) {
            const pointerEventProcessor = pointerEventProcessorList[i];
            const touchIndex = pointerEventProcessor.claimedTouchIdList.indexOf(touchID);
            if (touchIndex !== -1) {
              removeAt(pointerEventProcessor.claimedTouchIdList, touchIndex);
            }
          }
        }
        _updatePointerEventProcessorList() {
          const listToAdd = this._processorListToAdd;
          const addLength = listToAdd.length;
          for (let i = 0; i < addLength; ++i) {
            this.addPointerEventProcessor(listToAdd[i]);
          }
          listToAdd.length = 0;
          const listToRemove = this._processorListToRemove;
          const removeLength = listToRemove.length;
          for (let i = 0; i < removeLength; ++i) {
            this.removePointerEventProcessor(listToRemove[i]);
          }
          listToRemove.length = 0;
        }
        _sortPointerEventProcessorList() {
          if (!this._isListDirty) {
            return;
          }
          const pointerEventProcessorList = this._pointerEventProcessorList;
          const length = pointerEventProcessorList.length;
          for (let i = 0; i < length; ++i) {
            const pointerEventProcessor = pointerEventProcessorList[i];
            const node = pointerEventProcessor.node;
            if (node._uiProps) {
              const trans = node._uiProps.uiTransformComp;
              pointerEventProcessor.cachedCameraPriority = trans.cameraPriority;
            }
          }
          pointerEventProcessorList.sort(this._sortByPriority);
          this._isListDirty = false;
        }
        _sortByPriority(p1, p2) {
          const node1 = p1.node;
          const 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;
          }
          let n1 = node1;
          let n2 = node2;
          let 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;
            }
          }
          const priority1 = n1 ? n1.getSiblingIndex() : 0;
          const priority2 = n2 ? n2.getSiblingIndex() : 0;
          return ex ? priority1 - priority2 : priority2 - priority1;
        }
        _markListDirty() {
          this._isListDirty = true;
        }
      }
      new PointerEventDispatcher();

      const _dsInfo = new DescriptorSetInfo(null);
      const m4_1$4 = new Mat4();
      class Batcher2D {
        get nativeObj() {
          return this._nativeObj;
        }
        get currBufferAccessor() {
          if (this._staticVBBuffer) return this._staticVBBuffer;
          this._staticVBBuffer = this.switchBufferAccessor();
          return this._staticVBBuffer;
        }
        get batches() {
          return this._batches;
        }
        set currStaticRoot(value) {
          this._currStaticRoot = value;
        }
        set currIsStatic(value) {
          this._currIsStatic = value;
        }
        constructor(_root) {
          this._screens = [];
          this._staticVBBuffer = null;
          this._bufferAccessors = new Map();
          this._currBID = -1;
          this._indexStart = 0;
          this._emptyMaterial = new Material$1();
          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(() => new DrawBatch2D(), 128, obj => obj.destroy(this));
        }
        initialize() {
          return true;
        }
        destroy() {
          for (let i = 0; i < this._batches.length; i++) {
            if (this._batches.array[i]) {
              this._batches.array[i].destroy(this);
            }
          }
          this._batches.destroy();
          for (const accessor of this._bufferAccessors.values()) {
            accessor.destroy();
          }
          this._bufferAccessors.clear();
          if (this._drawBatchPool) {
            this._drawBatchPool.destroy();
          }
          this._descriptorSetCache.destroy();
          StencilManager.sharedManager.destroy();
          if (this._maskClearModel && this._maskModelMesh) {
            cclegacy.director.root.destroyModel(this._maskClearModel);
            this._maskModelMesh.destroy();
          }
          if (this._maskClearMtl) {
            this._maskClearMtl.destroy();
          }
        }
        syncRootNodesToNative() {
          {
            const rootNodes = [];
            for (const screen of this._screens) {
              rootNodes.push(screen.node);
            }
            this._nativeObj.syncRootNodesToNative(rootNodes);
          }
        }
        addScreen(comp) {
          this._screens.push(comp);
          this._screens.sort(this._screenSort);
          {
            this.syncRootNodesToNative();
          }
        }
        removeScreen(comp) {
          const idx = this._screens.indexOf(comp);
          if (idx === -1) {
            return;
          }
          this._screens.splice(idx, 1);
          {
            this.syncRootNodesToNative();
          }
        }
        sortScreens() {
          this._screens.sort(this._screenSort);
          {
            this.syncRootNodesToNative();
          }
        }
        getFirstRenderCamera(node) {
          if (node.scene && node.scene.renderScene) {
            const cameras = node.scene.renderScene.cameras;
            for (let i = 0; i < cameras.length; i++) {
              const camera = cameras[i];
              if (camera.visibility & node.layer) {
                return camera;
              }
            }
          }
          return null;
        }
        update() {
          {
            return;
          }
        }
        uploadBuffers() {
          {
            this._nativeObj.uploadBuffers();
          }
        }
        reset() {
          {
            this._nativeObj.reset();
          }
        }
        switchBufferAccessor(attributes = vfmtPosUvColor) {
          const strideBytes = attributes === vfmtPosUvColor ? 36 : getAttributeStride(attributes);
          if (!this._staticVBBuffer || this._staticVBBuffer.vertexFormatBytes !== strideBytes) {
            let 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;
        }
        registerBufferAccessor(key, accessor) {
          this._bufferAccessors.set(key, accessor);
        }
        updateBuffer(attributes, bid) {
          const accessor = this.switchBufferAccessor(attributes);
          if (this._currBID !== bid) {
            this._currBID = bid;
            this._indexStart = accessor.getMeshBuffer(bid).indexOffset;
          }
        }
        commitComp(comp, renderData, frame, assembler, transform) {
          let dataHash = 0;
          let mat;
          let bufferID = -1;
          if (renderData && renderData.chunk) {
            if (!renderData.isValid()) return;
            dataHash = renderData.dataHash;
            mat = renderData.material;
            bufferID = renderData.chunk.bufferId;
          }
          if (comp.stencilStage === 2 || comp.stencilStage === 6) {
            this._insertMaskBatch(comp);
          } else {
            comp.stencilStage = StencilManager.sharedManager.stage;
          }
          const 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);
        }
        commitIA(renderComp, ia, tex, mat, transform) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          let depthStencil = null;
          let 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);
          }
          const 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);
        }
        commitMiddleware(comp, meshBuffer, indexOffset, indexCount, tex, mat, enableBatch) {
          const 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;
        }
        commitModel(comp, model, mat) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          let depthStencil = null;
          let dssHash = 0;
          if (mat) {
            if (comp.stencilStage === 2 || comp.stencilStage === 6) {
              this._insertMaskBatch(comp);
            } else {
              comp.stencilStage = StencilManager.sharedManager.stage;
            }
            depthStencil = StencilManager.sharedManager.getStencilStage(comp.stencilStage, mat);
            dssHash = StencilManager.sharedManager.getStencilHash(comp.stencilStage);
          }
          const stamp = cclegacy.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (let i = 0; i < model.subModels.length; i++) {
            const curDrawBatch = this._drawBatchPool.alloc();
            const 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);
          }
        }
        setupStaticBatch(staticComp, bufferAccessor) {
          this.finishMergeBatches();
          this._staticVBBuffer = bufferAccessor;
          this.currStaticRoot = staticComp;
        }
        endStaticBatch() {
          this.finishMergeBatches();
          this.currStaticRoot = null;
          this._staticVBBuffer = null;
          this.switchBufferAccessor();
        }
        commitStaticBatch(comp) {
          this._batches.concat(comp.drawBatchList);
          this.finishMergeBatches();
        }
        autoMergeBatches(renderComp) {
          if (this._currIsMiddleware) {
            this.mergeBatchesForMiddleware(renderComp);
            return;
          }
          const mat = this._currMaterial;
          if (!mat) {
            return;
          }
          let ia;
          const rd = this._currRenderData;
          const 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) {
            const bid = this._currBID;
            const buf = accessor.getMeshBuffer(bid);
            if (!buf) {
              return;
            }
            const 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 || !this._currTexture) {
            return;
          }
          let depthStencil = null;
          let 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);
          }
          const 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);
        }
        mergeBatchesForMiddleware(renderComp) {
          let depthStencil = null;
          let 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);
          const curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = renderComp.node.layer;
          const 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;
        }
        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);
        }
        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;
        }
        finishMergeBatches() {
          this.autoMergeBatches();
          this.resetRenderStates();
        }
        flushMaterial(mat) {
          this._currMaterial = mat;
        }
        walk(node, level = 0) {
          if (!node.activeInHierarchy) {
            return;
          }
          const children = node.children;
          const uiProps = node._uiProps;
          const render = uiProps.uiComp;
          const parentOpacity = this._pOpacity;
          let opacity = parentOpacity;
          const selfOpacity = render && render.color ? render.color.a / 255 : 1;
          this._pOpacity = opacity *= selfOpacity * uiProps.localOpacity;
          uiProps.setOpacity(opacity);
          if (!approx(opacity, 0, EPSILON$2)) {
            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);
              const buffer = render.renderData.getMeshBuffer();
              if (buffer) {
                buffer.setDirty();
              }
            }
            if (children.length > 0 && !node._static) {
              for (let i = 0; i < children.length; ++i) {
                const 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 === 2 || render.stencilStage === 6) && StencilManager.sharedManager.getMaskStackSize() > 0) {
              this.autoMergeBatches(this._currComponent);
              this.resetRenderStates();
              StencilManager.sharedManager.exitMask();
            }
          }
          level += 1;
        }
        _screenSort(a, b) {
          return a.node.getSiblingIndex() - b.node.getSiblingIndex();
        }
        _releaseDescriptorSetCache(textureHash, sampler = null) {
          {
            this._nativeObj.releaseDescriptorSetCache(textureHash, sampler);
          }
        }
        _createClearModel() {
          if (!this._maskClearModel) {
            this._maskClearMtl = builtinResMgr.get('default-clear-stencil');
            this._maskClearModel = cclegacy.director.root.createModel(Model);
            const stride = getAttributeStride(vfmt);
            const gfxDevice = deviceManager.gfxDevice;
            const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(8 | 2, 1, 4 * stride, stride));
            const vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]);
            vertexBuffer.update(vb);
            const indexBuffer = gfxDevice.createBuffer(new BufferInfo(4 | 2, 1, 6 * 2, 2));
            const ib = new Uint16Array([0, 1, 2, 2, 1, 3]);
            indexBuffer.update(ib);
            this._maskModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, 7, indexBuffer);
            this._maskModelMesh.subMeshIdx = 0;
            this._maskClearModel.initSubModel(0, this._maskModelMesh, this._maskClearMtl);
          }
        }
        _insertMaskBatch(comp) {
          this.autoMergeBatches(this._currComponent);
          this.resetRenderStates();
          this._createClearModel();
          this._maskClearModel.node = this._maskClearModel.transform = comp.node;
          const _stencilManager = StencilManager.sharedManager;
          _stencilManager.pushMask(1);
          const stage = _stencilManager.clear(comp);
          let depthStencil = null;
          let dssHash = 0;
          const mat = this._maskClearMtl;
          if (mat) {
            depthStencil = _stencilManager.getStencilStage(stage, mat);
            dssHash = _stencilManager.getStencilHash(stage);
          }
          const model = this._maskClearModel;
          const stamp = cclegacy.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (let i = 0; i < model.subModels.length; i++) {
            const curDrawBatch = this._drawBatchPool.alloc();
            const 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();
        }
        syncMeshBuffersToNative(accId, buffers) {
          {
            const nativeBuffers = buffers.map(buf => buf.nativeObj);
            this._nativeObj.syncMeshBuffersToNative(accId, nativeBuffers);
          }
        }
      } exports("UI", Batcher2D);
      class LocalDescriptorSet {
        get descriptorSet() {
          return this._descriptorSet;
        }
        constructor() {
          this._descriptorSet = null;
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
          this._localBuffer = null;
          this._transformUpdate = true;
          const device = deviceManager.gfxDevice;
          this._localData = new Float32Array(56);
          this._localBuffer = device.createBuffer(new BufferInfo(16 | 2, 2 | 1, 224, 224));
        }
        initialize(batch) {
          const 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);
          const binding = 12;
          this._descriptorSet.bindTexture(binding, batch.texture);
          this._descriptorSet.bindSampler(binding, batch.sampler);
          this._descriptorSet.update();
          this._transformUpdate = true;
        }
        updateTransform(transform) {
          if (transform === this._transform) return;
          this._transform = transform;
          this._transformUpdate = true;
          this.uploadLocalData();
        }
        equals(transform, textureHash, samplerHash) {
          return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash;
        }
        reset() {
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
        }
        destroy() {
          if (this._localBuffer) {
            this._localBuffer.destroy();
            this._localBuffer = null;
          }
          if (this._descriptorSet) {
            this._descriptorSet.destroy();
            this._descriptorSet = null;
          }
          this._localData = null;
        }
        isValid() {
          return this._transform && this._transform.isValid;
        }
        uploadLocalData() {
          const node = this._transform;
          if (node.hasChangedFlags || node.isTransformDirty()) {
            node.updateWorldTransform();
            this._transformUpdate = true;
          }
          if (this._transformUpdate) {
            const worldMatrix = node.worldMatrix;
            Mat4.toArray(this._localData, worldMatrix, 0);
            Mat4.invert(m4_1$4, worldMatrix);
            Mat4.transpose(m4_1$4, m4_1$4);
            Mat4.toArray(this._localData, m4_1$4, 16);
            this._localBuffer.update(this._localData);
            this._transformUpdate = false;
          }
        }
      }
      class DescriptorSetCache {
        constructor() {
          this._descriptorSetCache = new Map();
          this._dsCacheHashByTexture = new Map();
          this._localDescriptorSetCache = [];
          this._localCachePool = new Pool(() => new LocalDescriptorSet(), 16, obj => obj.destroy());
        }
        getDescriptorSet(batch) {
          cclegacy.director.root;
          if (batch.useLocalData) {
            const caches = this._localDescriptorSetCache;
            for (let i = 0, len = caches.length; i < len; i++) {
              const cache = caches[i];
              if (cache.equals(batch.useLocalData, batch.textureHash, batch.samplerHash)) {
                return cache.descriptorSet;
              }
            }
            const localDs = this._localCachePool.alloc();
            localDs.initialize(batch);
            this._localDescriptorSetCache.push(localDs);
            return localDs.descriptorSet;
          } else {
            const hash = batch.textureHash ^ batch.samplerHash;
            if (this._descriptorSetCache.has(hash)) {
              return this._descriptorSetCache.get(hash);
            } else {
              _dsInfo.layout = batch.passes[0].localSetLayout;
              const descriptorSet = deviceManager.gfxDevice.createDescriptorSet(_dsInfo);
              const binding = 12;
              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;
            }
          }
        }
        update() {
          const caches = this._localDescriptorSetCache;
          const length = caches.length;
          if (length === 0) {
            return;
          }
          const uselessArray = [];
          for (let i = 0; i < length; i++) {
            const value = caches[i];
            if (value.isValid()) {
              value.uploadLocalData();
            } else {
              value.reset();
              const pos = caches.indexOf(value);
              uselessArray.push(pos);
            }
          }
          for (let i = uselessArray.length - 1; i >= 0; i--) {
            const index = uselessArray[i];
            const localDs = caches[index];
            caches.splice(index, 1);
            this._localCachePool.free(localDs);
          }
        }
        reset() {
          const caches = this._localDescriptorSetCache;
          const length = caches.length;
          for (let i = 0; i < length; i++) {
            const value = caches[i];
            this._localCachePool.free(value);
          }
          this._localDescriptorSetCache.length = 0;
        }
        releaseDescriptorSetCache(textureHash) {
          const key = this._dsCacheHashByTexture.get(textureHash);
          if (key && this._descriptorSetCache.has(key)) {
            this._descriptorSetCache.get(key).destroy();
            this._descriptorSetCache.delete(key);
            this._dsCacheHashByTexture.delete(textureHash);
          }
        }
        destroy() {
          for (const value of this._descriptorSetCache.values()) {
            value.destroy();
          }
          this._descriptorSetCache.clear();
          this._dsCacheHashByTexture.clear();
          this._localDescriptorSetCache.length = 0;
          this._localCachePool.destroy();
        }
      }
      cclegacy.internal.Batcher2D = Batcher2D;

      class UIDrawBatch extends DrawBatch2D {} exports("UIDrawBatch", UIDrawBatch);
      markAsWarning(MeshBuffer.prototype, 'MeshBuffer', ['byteStart', 'vertexStart', 'indicesStart', 'request'].map(item => ({
        name: item,
        suggest: `please use meshBuffer.accessor.${item} instead`
      })));
      replaceProperty(MeshBuffer.prototype, 'MeshBuffer', [{
        name: 'indicesOffset',
        newName: 'indexOffset'
      }]);
      removeProperty(MeshBuffer.prototype, 'MeshBuffer', [{
        name: 'vertexBuffers'
      }, {
        name: 'indexBuffer'
      }]);
      replaceProperty(Batcher2D.prototype, 'Batcher2D', [{
        name: 'currBufferBatch',
        newName: 'currBufferAccessor'
      }, {
        name: 'acquireBufferBatch',
        newName: 'switchBufferAccessor'
      }]);
      removeProperty(MeshRenderData.prototype, 'MeshRenderData', [{
        name: 'formatByte'
      }, {
        name: 'byteStart'
      }, {
        name: 'byteCount'
      }]);
      replaceProperty(MeshRenderData.prototype, 'MeshRenderData', [{
        name: 'indicesStart',
        newName: 'indexStart'
      }]);
      class QuadRenderData extends MeshRenderData {
        constructor(vertexFormat) {
          super(vertexFormat);
          warnID(9006);
        }
      } exports("QuadRenderData", QuadRenderData);

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

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

      var _dec$1P, _dec2$1e, _class$1P, _class2$1z, _initializer$1t, _initializer2$19;
      const MAX_INT16 = (1 << 15) - 1;
      const MIN_INT16 = -1 << 15;
      let Sorting = exports("Sorting", (_dec$1P = ccclass$H('cc.Sorting'), _dec2$1e = type$a(SortingLayers.Enum), _dec$1P(_class$1P = disallowMultiple$1(_class$1P = (_class2$1z = class Sorting extends Component {
        constructor() {
          super();
          this._sortingLayer = _initializer$1t && _initializer$1t();
          this._sortingOrder = _initializer2$19 && _initializer2$19();
          this._modelRenderer = null;
        }
        get sortingLayer() {
          return this._sortingLayer;
        }
        set sortingLayer(val) {
          if (val === this._sortingLayer || !SortingLayers.isLayerValid(val)) return;
          this._sortingLayer = val;
          this._updateSortingPriority();
        }
        get sortingOrder() {
          return this._sortingOrder;
        }
        set sortingOrder(val) {
          if (val === this._sortingOrder) return;
          this._sortingOrder = clamp$1(val, MIN_INT16, MAX_INT16);
          this._updateSortingPriority();
        }
        __preload() {
          this._modelRenderer = this.getComponent('cc.ModelRenderer');
          if (!this._modelRenderer) {
            warnID(16301, this.node.name);
          }
          this._updateSortingPriority();
        }
        _updateSortingPriority() {
          const sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer);
          const sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder);
          if (this._modelRenderer && this._modelRenderer.isValid) {
            this._modelRenderer.priority = sortingPriority;
          }
        }
      }, (_applyDecoratedDescriptor(_class2$1z.prototype, "sortingLayer", [_dec2$1e], Object.getOwnPropertyDescriptor(_class2$1z.prototype, "sortingLayer"), _class2$1z.prototype), _initializer$1t = applyDecoratedInitializer(_class2$1z.prototype, "_sortingLayer", [serializable$l], function () {
        return SortingLayers.Enum.default;
      }), _initializer2$19 = applyDecoratedInitializer(_class2$1z.prototype, "_sortingOrder", [serializable$l], function () {
        return 0;
      })), _class2$1z)) || _class$1P) || _class$1P));

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

      var _dec$1O, _class$1O, _class2$1y, _initializer$1s, _initializer2$18, _initializer3$P, _initializer4$J;
      (_dec$1O = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}EmbeddedPlayer`), _dec$1O(_class$1O = (_class2$1y = class EmbeddedPlayer extends EditorExtendable {
        constructor(...args) {
          super(...args);
          this.begin = _initializer$1s && _initializer$1s();
          this.end = _initializer2$18 && _initializer2$18();
          this.reconciledSpeed = _initializer3$P && _initializer3$P();
          this.playable = _initializer4$J && _initializer4$J();
        }
      }, (_initializer$1s = applyDecoratedInitializer(_class2$1y.prototype, "begin", [serializable$l], function () {
        return 0.0;
      }), _initializer2$18 = applyDecoratedInitializer(_class2$1y.prototype, "end", [serializable$l], function () {
        return 0.0;
      }), _initializer3$P = applyDecoratedInitializer(_class2$1y.prototype, "reconciledSpeed", [serializable$l], function () {
        return false;
      }), _initializer4$J = applyDecoratedInitializer(_class2$1y.prototype, "playable", [serializable$l], function () {
        return null;
      })), _class2$1y)) || _class$1O);
      class EmbeddedPlayable {}
      class EmbeddedPlayableState {
        constructor(randomAccess) {
          this._randomAccess = randomAccess;
        }
        get randomAccess() {
          return this._randomAccess;
        }
        setTime(_time) {}
      }

      class Playable {
        constructor() {
          this._isPlaying = false;
          this._isPaused = false;
          this._stepOnce = false;
        }
        get isPlaying() {
          return this._isPlaying;
        }
        get isPaused() {
          return this._isPaused;
        }
        get isMotionless() {
          return !this.isPlaying || this.isPaused;
        }
        play() {
          if (this._isPlaying) {
            if (this._isPaused) {
              this._isPaused = false;
              this.onResume();
            } else {
              this.onError(getError(3912));
            }
          } else {
            this._isPlaying = true;
            this.onPlay();
          }
        }
        stop() {
          if (this._isPlaying) {
            this._isPlaying = false;
            this.onStop();
            this._isPaused = false;
          }
        }
        pause() {
          if (this._isPlaying && !this._isPaused) {
            this._isPaused = true;
            this.onPause();
          }
        }
        resume() {
          if (this._isPlaying && this._isPaused) {
            this._isPaused = false;
            this.onResume();
          }
        }
        step() {
          this.pause();
          this._stepOnce = true;
          if (!this._isPlaying) {
            this.play();
          }
        }
        update(deltaTime) {}
        onPlay() {}
        onPause() {}
        onResume() {}
        onStop() {}
        onError(message) {}
      }

      const WrapMode = {
        "Default": 0,
        "Normal": 1,
        "Reverse": 36,
        "Loop": 2,
        "LoopReverse": 38,
        "PingPong": 22,
        "PingPongReverse": 54
      };
      ccenum(WrapMode);
      class WrappedInfo {
        constructor(info) {
          this.ratio = 0;
          this.time = 0;
          this.direction = 1;
          this.stopped = true;
          this.iterations = 0;
          this.frameIndex = undefined;
          if (info) {
            this.set(info);
          }
        }
        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;
        }
      }
      function isLerpable(object) {
        return typeof object.lerp === 'function';
      }

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

      function getGlobalAnimationManager() {
        const animationManager = cclegacy.director.getAnimationManager();
        return animationManager;
      }

      const AnimationStateEventType = {
        "PLAY": "play",
        "STOP": "stop",
        "PAUSE": "pause",
        "RESUME": "resume",
        "LASTFRAME": "lastframe",
        "FINISHED": "finished"
      };
      ccenum(AnimationStateEventType);
      let AnimationState$1 = class AnimationState extends Playable {
        get clip() {
          return this._clip;
        }
        get name() {
          return this._name;
        }
        get length() {
          return this.duration;
        }
        get wrapMode() {
          return this._wrapMode;
        }
        set wrapMode(value) {
          var _this$_clipEventEval;
          this._wrapMode = value;
          this.time = 0;
          if (value & 2) {
            this.repeatCount = Infinity;
          } else {
            this.repeatCount = 1;
          }
          (_this$_clipEventEval = this._clipEventEval) === null || _this$_clipEventEval === void 0 ? void 0 : _this$_clipEventEval.setWrapMode(value);
        }
        get repeatCount() {
          return this._repeatCount;
        }
        set repeatCount(value) {
          this._repeatCount = value;
          const shouldWrap = this._wrapMode & 4;
          const reverse = (this.wrapMode & 36) === 36;
          if (value === Infinity && !shouldWrap && !reverse) {
            this._useSimpleProcess = true;
          } else {
            this._useSimpleProcess = false;
          }
        }
        get delay() {
          return this._delay;
        }
        set delay(value) {
          this._delayTime = this._delay = value;
        }
        get playbackRange() {
          return this._playbackRange;
        }
        set playbackRange(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);
        }
        get speed() {
          return this._speed;
        }
        set speed(value) {
          var _this$_clipEmbeddedPl;
          this._speed = value;
          (_this$_clipEmbeddedPl = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl === void 0 ? void 0 : _this$_clipEmbeddedPl.notifyHostSpeedChanged(value);
        }
        get current() {
          return this.getWrappedInfo(this.time).time;
        }
        get ratio() {
          return this.duration === 0.0 ? 0.0 : this.current / this.duration;
        }
        get weight() {
          return this._weight;
        }
        set weight(value) {
          this._weight = value;
          if (this._poseOutput) {
            this._poseOutput.weight = value;
          }
        }
        constructor(clip, name = '') {
          super();
          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 = 1;
          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.`);
          }
        }
        get curveLoaded() {
          return this._curveLoaded;
        }
        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;
          const 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 & 2) === 2) {
            this.repeatCount = Infinity;
          } else {
            this.repeatCount = 1;
          }
          if (!this._doNotCreateEval) {
            var _ref, _getGlobalAnimationMa, _this$_poseOutput;
            const 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
            });
          }
          {
            if (clip.containsAnyEvent()) {
              this._clipEventEval = clip.createEventEvaluator(this._targetNode);
            }
          }
          if (clip.containsAnyEmbeddedPlayer()) {
            this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode);
            this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed);
          }
        }
        destroy() {
          if (!this.isMotionless) {
            getGlobalAnimationManager().removeAnimation(this);
          }
          if (this._poseOutput) {
            this._poseOutput.destroy();
            this._poseOutput = null;
          }
          this._clipEval = undefined;
        }
        emit(...args) {
          getGlobalAnimationManager().pushDelayEvent(this._emit, this, args);
        }
        on(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.on(type, callback, target);
          } else {
            return null;
          }
        }
        once(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.once(type, callback, target);
          } else {
            return null;
          }
        }
        off(type, callback, target) {
          if (this._target && this._target.isValid) {
            this._target.off(type, callback, target);
          }
        }
        allowLastFrameEvent(allowed) {
          this._allowLastFrame = allowed;
        }
        _setEventTarget(target) {
          this._target = target;
        }
        setTime(time) {
          this._currentFramePlayed = false;
          this.time = time || 0.0;
          {
            var _this$_clipEventEval2;
            const info = this.getWrappedInfo(time, this._wrappedInfo);
            (_this$_clipEventEval2 = this._clipEventEval) === null || _this$_clipEventEval2 === void 0 ? void 0 : _this$_clipEventEval2.ignore(info.ratio, info.direction);
          }
        }
        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();
        }
        sample() {
          const info = this.getWrappedInfo(this.time, this._wrappedInfo);
          this._sampleCurves(info.time);
          {
            this._sampleEvents(info);
          }
          this._sampleEmbeddedPlayers(info);
          return info;
        }
        onPlay() {
          var _this$_clipEmbeddedPl2;
          this.setTime(this._getPlaybackStart());
          this._delayTime = this._delay;
          this._onReplayOrResume();
          this.emit("play", this);
          (_this$_clipEmbeddedPl2 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl2 === void 0 ? void 0 : _this$_clipEmbeddedPl2.notifyHostPlay(this.current);
        }
        onStop() {
          var _this$_clipEmbeddedPl3;
          if (!this.isPaused) {
            this._onPauseOrStop();
          }
          this.emit("stop", this);
          (_this$_clipEmbeddedPl3 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl3 === void 0 ? void 0 : _this$_clipEmbeddedPl3.notifyHostStop();
        }
        onResume() {
          var _this$_clipEmbeddedPl4;
          this._onReplayOrResume();
          this.emit("resume", this);
          (_this$_clipEmbeddedPl4 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl4 === void 0 ? void 0 : _this$_clipEmbeddedPl4.notifyHostPlay(this.current);
        }
        onPause() {
          var _this$_clipEmbeddedPl5;
          this._onPauseOrStop();
          this.emit("pause", this);
          (_this$_clipEmbeddedPl5 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl5 === void 0 ? void 0 : _this$_clipEmbeddedPl5.notifyHostPause(this.current);
        }
        _sampleCurves(time) {
          const {
            _poseOutput: poseOutput,
            _clipEval: clipEval
          } = this;
          if (poseOutput) {
            poseOutput.weight = this.weight;
          }
          if (clipEval) {
            clipEval.evaluate(time);
          }
        }
        _process() {
          if (this._useSimpleProcess) {
            this.simpleProcess();
          } else {
            this.process();
          }
        }
        process() {
          const info = this.sample();
          if (this._allowLastFrame) {
            let 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("lastframe", this);
            }
            lastInfo.set(info);
          }
          if (info.stopped) {
            this.stop();
            this.emit("finished", this);
          }
        }
        simpleProcess() {
          const playbackStart = this._playbackRange.min;
          const playbackDuration = this._playbackDuration;
          let time = 0.0;
          let ratio = 0.0;
          if (playbackDuration !== 0.0) {
            time = this.time % playbackDuration;
            if (time < 0.0) {
              time += playbackDuration;
            }
            const realTime = playbackStart + time;
            ratio = realTime * this._invDuration;
          }
          this._sampleCurves(playbackStart + time);
          if (this._clipEventEval || this._clipEmbeddedPlayerEval) {
            const 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("lastframe", this);
            }
            this._lastIterations = ratio;
          }
        }
        _needReverse(currentIterations) {
          const wrapMode = this.wrapMode;
          let needReverse = false;
          if ((wrapMode & 22) === 22) {
            const isEnd = currentIterations - (currentIterations | 0) === 0;
            if (isEnd && currentIterations > 0) {
              currentIterations -= 1;
            }
            const isOddIteration = currentIterations & 1;
            if (isOddIteration) {
              needReverse = !needReverse;
            }
          }
          if ((wrapMode & 36) === 36) {
            needReverse = !needReverse;
          }
          return needReverse;
        }
        getWrappedInfo(time, info) {
          info = info || new WrappedInfo();
          const {
            _playbackRange: {
              min: playbackStart
            },
            _playbackDuration: playbackDuration
          } = this;
          const 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;
          }
          let stopped = false;
          time -= playbackStart;
          let currentIterations = time > 0 ? time / playbackDuration : -(time / playbackDuration);
          if (currentIterations >= repeatCount) {
            currentIterations = repeatCount;
            stopped = true;
            let tempRatio = repeatCount - (repeatCount | 0);
            if (tempRatio === 0) {
              tempRatio = 1;
            }
            time = tempRatio * playbackDuration * (time > 0 ? 1 : -1);
          }
          if (time > playbackDuration) {
            const tempTime = time % playbackDuration;
            time = tempTime === 0 ? playbackDuration : tempTime;
          } else if (time < 0) {
            time %= playbackDuration;
            if (time !== 0) {
              time += playbackDuration;
            }
          }
          let needReverse = false;
          const shouldWrap = this._wrapMode & 4;
          if (shouldWrap) {
            needReverse = this._needReverse(currentIterations);
          }
          let 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;
        }
        _getPlaybackStart() {
          return this._playbackRange.min;
        }
        _sampleEvents(wrapInfo) {
          var _this$_clipEventEval3;
          (_this$_clipEventEval3 = this._clipEventEval) === null || _this$_clipEventEval3 === void 0 ? void 0 : _this$_clipEventEval3.sample(wrapInfo.ratio, wrapInfo.direction, wrapInfo.iterations);
        }
        _sampleEmbeddedPlayers(wrapInfo) {
          var _this$_clipEmbeddedPl6;
          (_this$_clipEmbeddedPl6 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl6 === void 0 ? void 0 : _this$_clipEmbeddedPl6.evaluate(wrapInfo.time, Math.trunc(wrapInfo.iterations));
        }
        _emit(type, state) {
          if (this._target && this._target.isValid) {
            this._target.emit(type, type, state);
          }
        }
        _onReplayOrResume() {
          getGlobalAnimationManager().addAnimation(this);
        }
        _onPauseOrStop() {
          getGlobalAnimationManager().removeAnimation(this);
        }
      }; exports("AnimationState", AnimationState$1);
      cclegacy.AnimationState = AnimationState$1;

      var _dec$1N, _class$1N, _class2$1x, _initializer$1r, _initializer2$17;
      (_dec$1N = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}EmbeddedAnimationClipPlayable`), _dec$1N(_class$1N = (_class2$1x = class EmbeddedAnimationClipPlayable extends EmbeddedPlayable {
        constructor(...args) {
          super(...args);
          this.path = _initializer$1r && _initializer$1r();
          this.clip = _initializer2$17 && _initializer2$17();
        }
        instantiate(root) {
          const {
            clip,
            path
          } = this;
          if (!clip) {
            return null;
          }
          const clipRoot = root.getChildByPath(path);
          if (!clipRoot) {
            errorID(3938, path, root.getPathInHierarchy(), clip.name);
            return null;
          }
          const state = new AnimationState$1(clip);
          state.initialize(clipRoot);
          return new EmbeddedAnimationClipPlayableState(state);
        }
      }, (_initializer$1r = applyDecoratedInitializer(_class2$1x.prototype, "path", [serializable$l], function () {
        return '';
      }), _initializer2$17 = applyDecoratedInitializer(_class2$1x.prototype, "clip", [serializable$l], function () {
        return null;
      })), _class2$1x)) || _class$1N);
      class EmbeddedAnimationClipPlayableState extends EmbeddedPlayableState {
        constructor(animationState) {
          super(true);
          this._animationState = void 0;
          this._animationState = animationState;
        }
        destroy() {
          this._animationState.destroy();
        }
        play() {
          this._animationState.play();
        }
        pause() {
          this._animationState.pause();
        }
        stop() {
          this._animationState.stop();
        }
        setSpeed(speed) {
          this._animationState.speed = speed;
        }
        setTime(time) {
          this._animationState.time = time;
        }
      }

      var _dec$1M, _class$1M, _class2$1w, _initializer$1q;
      (_dec$1M = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}EmbeddedParticleSystemPlayable`), _dec$1M(_class$1M = (_class2$1w = class EmbeddedParticleSystemPlayable extends EmbeddedPlayable {
        constructor(...args) {
          super(...args);
          this.path = _initializer$1q && _initializer$1q();
        }
        instantiate(root) {
          const node = root.getChildByPath(this.path);
          if (!node) {
            warn(`Hierarchy path ${this.path} does not exists.`);
            return null;
          }
          const ParticleSystemConstructor = getClassByName(`cc.ParticleSystem`);
          if (!ParticleSystemConstructor) {
            warn(`Particle system is required for embedded particle system player.`);
            return null;
          }
          const particleSystem = node.getComponent(ParticleSystemConstructor);
          if (!particleSystem) {
            warn(`${this.path} does not includes a particle system component.`);
            return null;
          }
          return new EmbeddedParticleSystemPlayableState(particleSystem);
        }
      }, (_initializer$1q = applyDecoratedInitializer(_class2$1w.prototype, "path", [serializable$l], function () {
        return '';
      })), _class2$1w)) || _class$1M);
      class EmbeddedParticleSystemPlayableState extends EmbeddedPlayableState {
        constructor(particleSystem) {
          super(false);
          this._particleSystem = void 0;
          this._particleSystem = particleSystem;
        }
        destroy() {}
        play() {
          this._particleSystem.play();
        }
        pause() {
          this._particleSystem.stopEmitting();
        }
        stop() {
          this._particleSystem.stopEmitting();
        }
        setSpeed(speed) {
          this._particleSystem.simulationSpeed = speed;
        }
      }

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

      var _dec$1K, _class$1K, _class2$1u, _initializer$1o, _dec2$1c, _class4$m, _class5$l, _initializer2$15, _initializer3$O, _class6$7, _dec3$T, _class7$4, _class8$3, _initializer4$I, _dec4$C, _class10$2, _class11$2, _initializer5$x, _dec5$z, _class13$1, _class14$1, _initializer6$q;
      const normalizedFollowTag = Symbol('NormalizedFollow');
      const parseTrsPathTag = Symbol('ConvertAsTrsPath');
      const trackBindingTag = Symbol('TrackBinding');
      let TrackPath = (_dec$1K = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}TrackPath`), _dec$1K(_class$1K = (_class2$1u = class TrackPath {
        constructor() {
          this._paths = _initializer$1o && _initializer$1o();
        }
        get length() {
          return this._paths.length;
        }
        toProperty(name) {
          this._paths.push(name);
          return this;
        }
        toElement(index) {
          this._paths.push(index);
          return this;
        }
        toHierarchy(nodePath) {
          this._paths.push(new HierarchyPath(nodePath));
          return this;
        }
        toComponent(constructor) {
          const path = new ComponentPath(typeof constructor === 'string' ? constructor : getClassName(constructor));
          this._paths.push(path);
          return this;
        }
        toCustomized(resolver) {
          this._paths.push(resolver);
          return this;
        }
        append(...trackPaths) {
          const paths = this._paths.concat(...trackPaths.map(trackPath => trackPath._paths));
          this._paths = paths;
          return this;
        }
        isPropertyAt(index) {
          return typeof this._paths[index] === 'string';
        }
        parsePropertyAt(index) {
          return this._paths[index];
        }
        isElementAt(index) {
          return typeof this._paths[index] === 'number';
        }
        parseElementAt(index) {
          return this._paths[index];
        }
        isHierarchyAt(index) {
          return this._paths[index] instanceof HierarchyPath;
        }
        parseHierarchyAt(index) {
          assertIsTrue(this.isHierarchyAt(index));
          return this._paths[index].path;
        }
        isComponentAt(index) {
          return this._paths[index] instanceof ComponentPath;
        }
        parseComponentAt(index) {
          assertIsTrue(this.isComponentAt(index));
          return this._paths[index].component;
        }
        slice(beginIndex, endIndex) {
          const trackPath = new TrackPath();
          trackPath._paths = this._paths.slice(beginIndex, endIndex);
          return trackPath;
        }
        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);
        }
        [parseTrsPathTag]() {
          const {
            _paths: paths
          } = this;
          const nPaths = paths.length;
          let iPath = 0;
          let nodePath = '';
          for (; iPath < nPaths; ++iPath) {
            const 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;
          }
          let 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
          };
        }
        [normalizedFollowTag](root, beginIndex, endIndex) {
          const {
            _paths: paths
          } = this;
          let result = root;
          for (let iPath = beginIndex; iPath < endIndex; ++iPath) {
            const 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;
        }
      }, (_initializer$1o = applyDecoratedInitializer(_class2$1u.prototype, "_paths", [serializable$l], function () {
        return [];
      })), _class2$1u)) || _class$1K);
      let TrackBinding = (_dec2$1c = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}TrackBinding`), _dec2$1c(_class4$m = uniquelyReferenced(_class4$m = (_class5$l = (_class6$7 = class TrackBinding {
        constructor() {
          this.path = _initializer2$15 && _initializer2$15();
          this.proxy = _initializer3$O && _initializer3$O();
        }
        parseTrsPath() {
          if (this.proxy) {
            return null;
          } else {
            return this.path[parseTrsPathTag]();
          }
        }
        createRuntimeBinding(target, poseOutput, isConstant) {
          const {
            path,
            proxy
          } = this;
          const nPaths = path.length;
          const iLastPath = nPaths - 1;
          if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
            const lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
            const resultTarget = path[normalizedFollowTag](target, 0, nPaths - 1);
            if (resultTarget === null) {
              return null;
            }
            if (poseOutput && resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
              const blendStateWriter = poseOutput.createPoseWriter(resultTarget, lastPropertyKey, isConstant);
              return blendStateWriter;
            }
            let setValue;
            let getValue;
            {
              let animationFunction = TrackBinding._animationFunctions.get(resultTarget.constructor);
              if (!animationFunction) {
                animationFunction = new Map();
                TrackBinding._animationFunctions.set(resultTarget.constructor, animationFunction);
              }
              let 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,
              getValue
            };
          } else if (!proxy) {
            errorID(3921);
            return null;
          } else {
            const resultTarget = path[normalizedFollowTag](target, 0, nPaths);
            if (resultTarget === null) {
              return null;
            }
            const runtimeProxy = proxy.forTarget(resultTarget);
            if (!runtimeProxy) {
              return null;
            }
            const binding = {
              setValue: value => {
                runtimeProxy.set(value);
              }
            };
            const proxyGet = runtimeProxy.get;
            if (proxyGet) {
              binding.getValue = () => proxyGet.call(runtimeProxy);
            }
            return binding;
          }
        }
        isMaskedOff(mask) {
          const trsPath = this.parseTrsPath();
          if (!trsPath) {
            return false;
          }
          const joints = mask.joints[Symbol.iterator]();
          for (let jointMaskInfoIter = joints.next(); !jointMaskInfoIter.done; jointMaskInfoIter = joints.next()) {
            const {
              value: jointMaskInfo
            } = jointMaskInfoIter;
            if (jointMaskInfo.path !== trsPath.node) {
              continue;
            }
            return !jointMaskInfo.enabled;
          }
          return false;
        }
      }, _class6$7._animationFunctions = new WeakMap(), _class6$7), (_initializer2$15 = applyDecoratedInitializer(_class5$l.prototype, "path", [serializable$l], function () {
        return new TrackPath();
      }), _initializer3$O = applyDecoratedInitializer(_class5$l.prototype, "proxy", [serializable$l], null)), _class5$l)) || _class4$m) || _class4$m);
      function isTrsPropertyName(name) {
        return name === 'position' || name === 'rotation' || name === 'scale' || name === 'eulerAngles';
      }
      let Track = (_dec3$T = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}Track`), _dec3$T(_class7$4 = (_class8$3 = class Track {
        constructor() {
          this._binding = _initializer4$I && _initializer4$I();
        }
        get path() {
          return this._binding.path;
        }
        set path(value) {
          this._binding.path = value;
        }
        get proxy() {
          return this._binding.proxy;
        }
        set proxy(value) {
          this._binding.proxy = value;
        }
        get [trackBindingTag]() {
          return this._binding;
        }
        channels() {
          return [];
        }
        range() {
          const range = {
            min: Infinity,
            max: -Infinity
          };
          for (const channel of this.channels()) {
            range.min = Math.min(range.min, channel.curve.rangeMin);
            range.max = Math.max(range.max, channel.curve.rangeMax);
          }
          return range;
        }
      }, (_initializer4$I = applyDecoratedInitializer(_class8$3.prototype, "_binding", [serializable$l], function () {
        return new TrackBinding();
      })), _class8$3)) || _class7$4);
      let Channel = (_dec4$C = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}Channel`), _dec4$C(_class10$2 = (_class11$2 = class Channel {
        constructor(curve) {
          this.name = '';
          this._curve = _initializer5$x && _initializer5$x();
          this._curve = curve;
        }
        get curve() {
          return this._curve;
        }
      }, (_initializer5$x = applyDecoratedInitializer(_class11$2.prototype, "_curve", [serializable$l], null)), _class11$2)) || _class10$2);
      let SingleChannelTrack = (_dec5$z = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}SingleChannelTrack`), _dec5$z(_class13$1 = (_class14$1 = class SingleChannelTrack extends Track {
        constructor() {
          super();
          this._channel = _initializer6$q && _initializer6$q();
          this._channel = new Channel(this.createCurve());
        }
        get channel() {
          return this._channel;
        }
        channels() {
          return [this._channel];
        }
        createCurve() {
          throw new Error(`Not impl`);
        }
        [createEvalSymbol]() {
          const {
            curve
          } = this._channel;
          return new SingleChannelTrackEval(curve);
        }
      }, (_initializer6$q = applyDecoratedInitializer(_class14$1.prototype, "_channel", [serializable$l], null)), _class14$1)) || _class13$1);
      class SingleChannelTrackEval {
        constructor(_curve) {
          this._curve = _curve;
        }
        get requiresDefault() {
          return false;
        }
        evaluate(time) {
          return this._curve.evaluate(time);
        }
      }

      var _dec$1J, _class$1J, _class2$1t, _initializer$1n;
      const {
        ccclass: ccclass$E,
        serializable: serializable$i
      } = _decorator;
      (_dec$1J = ccclass$E(`${CLASS_NAME_PREFIX_ANIM}RealArrayTrack`), _dec$1J(_class$1J = (_class2$1t = class RealArrayTrack extends Track {
        constructor(...args) {
          super(...args);
          this._channels = _initializer$1n && _initializer$1n();
        }
        get elementCount() {
          return this._channels.length;
        }
        set elementCount(value) {
          const {
            _channels: channels
          } = this;
          const nChannels = channels.length;
          if (value < nChannels) {
            this._channels.splice(value);
          } else if (value > nChannels) {
            this._channels.push(...Array.from({
              length: value - nChannels
            }, () => new Channel(new RealCurve())));
          }
        }
        channels() {
          return this._channels;
        }
        [createEvalSymbol]() {
          return new RealArrayTrackEval(this._channels.map(({
            curve
          }) => curve));
        }
      }, (_initializer$1n = applyDecoratedInitializer(_class2$1t.prototype, "_channels", [serializable$i], function () {
        return [];
      })), _class2$1t)) || _class$1J);
      class RealArrayTrackEval {
        constructor(_curves) {
          this._curves = _curves;
          this._result = new Array(_curves.length).fill(0.0);
        }
        get requiresDefault() {
          return false;
        }
        evaluate(time) {
          const {
            _result: result
          } = this;
          const nElements = result.length;
          for (let iElement = 0; iElement < nElements; ++iElement) {
            result[iElement] = this._curves[iElement].evaluate(time);
          }
          return this._result;
        }
      }

      var _dec$1I, _class$1I, _class2$1s, _initializer$1m, _initializer2$14, _descriptor$2;
      let UniformProxyFactory = (_dec$1I = ccclass$H('cc.animation.UniformProxyFactory'), _dec$1I(_class$1I = (_class2$1s = class UniformProxyFactory {
        constructor(uniformName, passIndex) {
          this.passIndex = _initializer$1m && _initializer$1m();
          this.uniformName = _initializer2$14 && _initializer2$14();
          _initializerDefineProperty(this, "channelIndex", _descriptor$2, this);
          this.passIndex = passIndex || 0;
          this.uniformName = uniformName || '';
        }
        forTarget(target) {
          if (!(target instanceof Material$1)) {
            warnID(3940, target);
            return undefined;
          }
          const {
            passIndex,
            uniformName,
            channelIndex
          } = this;
          if (passIndex < 0 || passIndex >= target.passes.length) {
            warnID(3941, target.name, passIndex);
            return undefined;
          }
          const pass = target.passes[passIndex];
          const handle = pass.getHandle(uniformName);
          if (!handle) {
            warnID(3942, target.name, passIndex, uniformName);
            return undefined;
          }
          const type = Pass.getTypeFromHandle(handle);
          if (type < 26) {
            const realHandle = channelIndex === undefined ? handle : pass.getHandle(uniformName, channelIndex, 13);
            if (!realHandle) {
              warnID(3943, target.name, passIndex, uniformName, channelIndex);
              return undefined;
            }
            if (isUniformArray(pass, uniformName)) {
              return {
                set: value => {
                  pass.setUniformArray(realHandle, value);
                }
              };
            }
            return {
              set: value => {
                pass.setUniform(realHandle, value);
              }
            };
          } else {
            const binding = Pass.getBindingFromHandle(handle);
            const prop = pass.properties[uniformName];
            const texName = prop && prop.value ? `${prop.value}${getStringFromType(prop.type)}` : getDefaultFromType(prop.type);
            let dftTex = builtinResMgr.get(texName);
            if (!dftTex) {
              warn(`Illegal texture default value: ${texName}.`);
              dftTex = builtinResMgr.get('default-texture');
            }
            return {
              set: value => {
                if (!value) {
                  value = dftTex;
                }
                const 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()));
                }
              }
            };
          }
        }
      }, (_initializer$1m = applyDecoratedInitializer(_class2$1s.prototype, "passIndex", [serializable$l], function () {
        return 0;
      }), _initializer2$14 = applyDecoratedInitializer(_class2$1s.prototype, "uniformName", [serializable$l], function () {
        return '';
      }), _descriptor$2 = _applyDecoratedDescriptor(_class2$1s.prototype, "channelIndex", [float], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function () {
          return undefined;
        }
      })), _class2$1s)) || _class$1I);
      function isUniformArray(pass, name) {
        for (const block of pass.shaderInfo.blocks) {
          for (const uniform of block.members) {
            if (uniform.name === name) {
              return uniform.count > 1;
            }
          }
        }
        return false;
      }

      var _dec$1H, _class$1H, _class2$1r, _initializer$1l, _initializer2$13, _dec2$1b, _class4$l, _class5$k, _initializer3$N, _dec3$S, _class7$3;
      let MorphWeightValueProxy = (_dec$1H = ccclass$H('cc.animation.MorphWeightValueProxy'), _dec$1H(_class$1H = (_class2$1r = class MorphWeightValueProxy {
        constructor() {
          this.subMeshIndex = _initializer$1l && _initializer$1l();
          this.shapeIndex = _initializer2$13 && _initializer2$13();
        }
        forTarget(target) {
          return {
            set: value => {
              target.setWeight(value, this.subMeshIndex, this.shapeIndex);
            }
          };
        }
      }, (_initializer$1l = applyDecoratedInitializer(_class2$1r.prototype, "subMeshIndex", [serializable$l], function () {
        return 0;
      }), _initializer2$13 = applyDecoratedInitializer(_class2$1r.prototype, "shapeIndex", [serializable$l], function () {
        return 0;
      })), _class2$1r)) || _class$1H);
      let MorphWeightsValueProxy = (_dec2$1b = ccclass$H('cc.animation.MorphWeightsValueProxy'), _dec2$1b(_class4$l = (_class5$k = class MorphWeightsValueProxy {
        constructor() {
          this.subMeshIndex = _initializer3$N && _initializer3$N();
        }
        forTarget(target) {
          return {
            set: value => {
              target.setWeights(value, this.subMeshIndex);
            }
          };
        }
      }, (_initializer3$N = applyDecoratedInitializer(_class5$k.prototype, "subMeshIndex", [serializable$l], function () {
        return 0;
      })), _class5$k)) || _class4$l);
      let MorphWeightsAllValueProxy = (_dec3$S = ccclass$H('cc.animation.MorphWeightsAllValueProxy'), _dec3$S(_class7$3 = class MorphWeightsAllValueProxy {
        forTarget(target) {
          return {
            set: value => {
              var _target$mesh$struct$p, _target$mesh;
              const 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 (let iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                target.setWeights(value, iSubMesh);
              }
            }
          };
        }
      }) || _class7$3);

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

      var _dec$1G, _class$1G;
      let RealTrack = (_dec$1G = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}RealTrack`), _dec$1G(_class$1G = class RealTrack extends SingleChannelTrack {
        createCurve() {
          return new RealCurve();
        }
      }) || _class$1G);

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

      var _dec$1F, _class$1F, _class2$1q, _initializer$1k, _initializer2$12;
      const CHANNEL_NAMES$2 = ['X', 'Y', 'Z', 'W'];
      let VectorTrack = (_dec$1F = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}VectorTrack`), _dec$1F(_class$1F = (_class2$1q = class VectorTrack extends Track {
        constructor() {
          super();
          this._channels = _initializer$1k && _initializer$1k();
          this._nComponents = _initializer2$12 && _initializer2$12();
          this._channels = new Array(4);
          for (let i = 0; i < this._channels.length; ++i) {
            const channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$2[i];
            this._channels[i] = channel;
          }
        }
        get componentsCount() {
          return this._nComponents;
        }
        set componentsCount(value) {
          this._nComponents = value;
        }
        channels() {
          return this._channels;
        }
        [createEvalSymbol]() {
          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));
          }
        }
      }, (_initializer$1k = applyDecoratedInitializer(_class2$1q.prototype, "_channels", [serializable$l], null), _initializer2$12 = applyDecoratedInitializer(_class2$1q.prototype, "_nComponents", [serializable$l], function () {
        return 4;
      })), _class2$1q)) || _class$1F);
      class Vec2TrackEval {
        constructor(_x, _y) {
          this._result = new Vec2();
          this._x = _x;
          this._y = _y;
        }
        get requiresDefault() {
          return !this._x || !this._y;
        }
        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;
        }
      }
      class Vec3TrackEval {
        constructor(_x, _y, _z) {
          this._result = new Vec3();
          this._x = _x;
          this._y = _y;
          this._z = _z;
        }
        get requiresDefault() {
          return !this._x || !this._y || !this._z;
        }
        evaluate(time, defaultValue) {
          const {
            _x,
            _y,
            _z,
            _result
          } = this;
          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;
        }
      }
      class Vec4TrackEval {
        constructor(_x, _y, _z, _w) {
          this._result = new Vec4();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        get requiresDefault() {
          return !this._x || !this._y || !this._z || !this._w;
        }
        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;
        }
      }

      var _dec$1E, _class$1E;
      let QuatTrack = (_dec$1E = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}QuatTrack`), _dec$1E(_class$1E = class QuatTrack extends SingleChannelTrack {
        createCurve() {
          return new QuatCurve();
        }
        [createEvalSymbol]() {
          return new QuatTrackEval(this.channels()[0].curve);
        }
      }) || _class$1E);
      class QuatTrackEval {
        constructor(_curve) {
          this._result = new Quat();
          this._curve = _curve;
        }
        get requiresDefault() {
          return false;
        }
        evaluate(time) {
          this._curve.evaluate(time, this._result);
          return this._result;
        }
      }

      var _dec$1D, _class$1D, _class2$1p, _initializer$1j;
      const CHANNEL_NAMES$1 = ['Red', 'Green', 'Blue', 'Alpha'];
      let ColorTrack = (_dec$1D = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ColorTrack`), _dec$1D(_class$1D = (_class2$1p = class ColorTrack extends Track {
        constructor() {
          super();
          this._channels = _initializer$1j && _initializer$1j();
          this._channels = new Array(4);
          for (let i = 0; i < this._channels.length; ++i) {
            const channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$1[i];
            this._channels[i] = channel;
          }
        }
        channels() {
          return this._channels;
        }
        [createEvalSymbol]() {
          return new ColorTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve), maskIfEmpty(this._channels[3].curve));
        }
      }, (_initializer$1j = applyDecoratedInitializer(_class2$1p.prototype, "_channels", [serializable$l], null)), _class2$1p)) || _class$1D);
      class ColorTrackEval {
        constructor(_x, _y, _z, _w) {
          this._result = new Color$1();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        get requiresDefault() {
          return !this._x || !this._y || !this._z || !this._w;
        }
        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;
        }
      }

      var _dec$1C, _class$1C, _class2$1o, _initializer$1i;
      const CHANNEL_NAMES = ['Width', 'Height'];
      let SizeTrack = (_dec$1C = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}SizeTrack`), _dec$1C(_class$1C = (_class2$1o = class SizeTrack extends Track {
        constructor() {
          super();
          this._channels = _initializer$1i && _initializer$1i();
          this._channels = new Array(2);
          for (let i = 0; i < this._channels.length; ++i) {
            const channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES[i];
            this._channels[i] = channel;
          }
        }
        channels() {
          return this._channels;
        }
        [createEvalSymbol]() {
          return new SizeTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve));
        }
      }, (_initializer$1i = applyDecoratedInitializer(_class2$1o.prototype, "_channels", [serializable$l], null)), _class2$1o)) || _class$1C);
      class SizeTrackEval {
        constructor(_width, _height) {
          this._result = new Size$1();
          this._width = _width;
          this._height = _height;
        }
        get requiresDefault() {
          return !this._width || !this._height;
        }
        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;
        }
      }

      var _dec$1B, _class$1B;
      let ObjectTrack = (_dec$1B = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ObjectTrack`), _dec$1B(_class$1B = class ObjectTrack extends SingleChannelTrack {
        createCurve() {
          return new ObjectCurve();
        }
      }) || _class$1B);

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

      const VariableType = {
        "FLOAT": 0,
        "BOOLEAN": 1,
        "TRIGGER": 2,
        "INTEGER": 3,
        "VEC3_experimental": 4,
        "QUAT_experimental": 5
      };
      const createInstanceTag = Symbol('CreateInstance');
      class VarInstanceBase {
        constructor(type) {
          this._refs = [];
          this.type = type;
        }
        bind(fn, thisArg, ...args) {
          this._refs.push({
            fn: fn,
            thisArg,
            args
          });
          return this.getValue();
        }
        get value() {
          return this.getValue();
        }
        set value(value) {
          this.setValue(value);
          for (const {
            fn,
            thisArg,
            args
          } of this._refs) {
            fn.call(thisArg, value, ...args);
          }
        }
      }

      var _dec$1A, _class$1A, _class2$1n, _initializer$1h, _initializer2$11;
      let PlainVariable = (_dec$1A = ccclass$H('cc.animation.PlainVariable'), _dec$1A(_class$1A = (_class2$1n = class PlainVariable {
        constructor(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 0:
              this._value = 0.0;
              break;
            case 3:
              this._value = 0;
              break;
            case 1:
              this._value = false;
              break;
          }
        }
        get type() {
          return this._type;
        }
        get value() {
          return this._value;
        }
        set value(value) {
          {
            switch (this._type) {
              default:
                break;
              case 0:
                assertIsTrue(typeof value === 'number');
                break;
              case 3:
                assertIsTrue(Number.isInteger(value));
                break;
              case 1:
                assertIsTrue(typeof value === 'boolean');
                break;
            }
          }
          this._value = value;
        }
        [createInstanceTag]() {
          return new VarInstancePrimitive(this._type, this._value);
        }
      }, (_initializer$1h = applyDecoratedInitializer(_class2$1n.prototype, "_type", [serializable$l], function () {
        return 0;
      }), _initializer2$11 = applyDecoratedInitializer(_class2$1n.prototype, "_value", [serializable$l], function () {
        return 0.0;
      })), _class2$1n)) || _class$1A);
      class VarInstancePrimitive extends VarInstanceBase {
        constructor(type, value) {
          super(type);
          this._value = void 0;
          this._value = value;
        }
        getValue() {
          return this._value;
        }
        setValue(value) {
          this._value = value;
        }
      }

      var _dec$1z, _class$1z, _class2$1m, _initializer$1g;
      const TRIGGER_VARIABLE_FLAG_VALUE_START = 0;
      const TRIGGER_VARIABLE_FLAG_VALUE_MASK = 1;
      const TRIGGER_VARIABLE_FLAG_RESET_MODE_START = 1;
      const TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK = 6;
      const TRIGGER_VARIABLE_DEFAULT_FLAGS = 0;
      assertIsTrue((0 << TRIGGER_VARIABLE_FLAG_VALUE_START | 0 << TRIGGER_VARIABLE_FLAG_RESET_MODE_START) === TRIGGER_VARIABLE_DEFAULT_FLAGS);
      let TriggerVariable = (_dec$1z = ccclass$H('cc.animation.TriggerVariable'), _dec$1z(_class$1z = (_class2$1m = class TriggerVariable {
        constructor() {
          this._flags = _initializer$1g && _initializer$1g();
        }
        get type() {
          return 2;
        }
        get value() {
          return !!((this._flags & TRIGGER_VARIABLE_FLAG_VALUE_MASK) >> TRIGGER_VARIABLE_FLAG_VALUE_START);
        }
        set value(value) {
          if (value) {
            this._flags |= 1 << TRIGGER_VARIABLE_FLAG_VALUE_START;
          } else {
            this._flags &= ~(1 << TRIGGER_VARIABLE_FLAG_VALUE_START);
          }
        }
        get resetMode() {
          return (this._flags & TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK) >> TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
        }
        set resetMode(value) {
          this._flags &= ~TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK;
          this._flags |= value << TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
        }
        [createInstanceTag]() {
          return new VarInstanceTrigger(this.value, this.resetMode);
        }
      }, (_initializer$1g = applyDecoratedInitializer(_class2$1m.prototype, "_flags", [serializable$l], function () {
        return TRIGGER_VARIABLE_DEFAULT_FLAGS;
      })), _class2$1m)) || _class$1z);
      class VarInstanceTrigger extends VarInstanceBase {
        constructor(value, resetMode) {
          super(2);
          this.resetMode = 0;
          this._value = void 0;
          this.resetMode = resetMode;
          this._value = value;
        }
        getValue() {
          return this._value;
        }
        setValue(value) {
          this._value = value;
        }
      }

      var _dec$1y, _class$1y, _class2$1l, _initializer$1f;
      let Vec3Variable = (_dec$1y = ccclass$H('cc.animation.Vec3Variable'), _dec$1y(_class$1y = (_class2$1l = class Vec3Variable {
        constructor() {
          this._value = _initializer$1f && _initializer$1f();
        }
        get type() {
          return 4;
        }
        get value() {
          return this._value;
        }
        set value(value) {
          Vec3.copy(this._value, value);
        }
        [createInstanceTag]() {
          return new VarInstanceVec3(this.value);
        }
      }, (_initializer$1f = applyDecoratedInitializer(_class2$1l.prototype, "_value", [serializable$l], function () {
        return new Vec3();
      })), _class2$1l)) || _class$1y);
      class VarInstanceVec3 extends VarInstanceBase {
        constructor(value) {
          super(4);
          this._value = new Vec3();
          Vec3.copy(this._value, value);
        }
        getValue() {
          return this._value;
        }
        setValue(value) {
          assertIsTrue(value instanceof Vec3);
          Vec3.copy(this._value, value);
        }
      }

      var _dec$1x, _class$1x, _class2$1k, _initializer$1e;
      let QuatVariable = (_dec$1x = ccclass$H('cc.animation.QuatVariable'), _dec$1x(_class$1x = (_class2$1k = class QuatVariable {
        constructor() {
          this._value = _initializer$1e && _initializer$1e();
        }
        get type() {
          return 5;
        }
        get value() {
          return this._value;
        }
        set value(value) {
          Quat.copy(this._value, value);
        }
        [createInstanceTag]() {
          return new VarInstanceQuat(this._value);
        }
      }, (_initializer$1e = applyDecoratedInitializer(_class2$1k.prototype, "_value", [serializable$l], function () {
        return new Quat();
      })), _class2$1k)) || _class$1x);
      class VarInstanceQuat extends VarInstanceBase {
        constructor(value) {
          super(5);
          this._value = new Quat();
          Quat.copy(this._value, value);
        }
        getValue() {
          return this._value;
        }
        setValue(value) {
          assertIsTrue(value instanceof Quat);
          Quat.copy(this._value, value);
        }
      }

      function createVariable(type, initialValue) {
        let variable;
        switch (type) {
          case 0:
          case 3:
          case 1:
            variable = new PlainVariable(type);
            break;
          case 2:
            variable = new TriggerVariable();
            break;
          case 4:
            variable = new Vec3Variable();
            break;
          case 5:
            variable = new QuatVariable();
            break;
          default:
            throw new Error(`Unknown variable type ${type}`);
        }
        if (typeof initialValue !== 'undefined') {
          variable.value = initialValue;
        }
        return variable;
      }

      class InvalidTransitionError extends Error {
        constructor(type) {
          super(`${type} transition is invalid`);
          this.name = 'TransitionRejectError';
        }
      }
      class VariableNotDefinedError extends Error {
        constructor(name) {
          super(`Graph variable ${name} is not defined`);
        }
      }
      class VariableTypeMismatchedError extends Error {
        constructor(name, expected, received) {
          super(`Expect graph variable ${name} to have type '${expected}' instead of received '${received !== null && received !== void 0 ? received : typeof received}'`);
        }
      }

      const Destroyed = CCObject.Flags.Destroyed;
      const PersistentMask = CCObject.Flags.PersistentMask;
      const objsToClearTmpVar = [];
      function hasImplementedInstantiate(original) {
        return typeof original._instantiate === 'function';
      }
      function instantiate(original, internalForce) {
        let clone;
        if (isCCObject(original)) {
          if (hasImplementedInstantiate(original)) {
            cclegacy.game._isCloning = true;
            clone = original._instantiate(null, true);
            cclegacy.game._isCloning = false;
            {
              updateChildrenForDeserialize(clone);
            }
            return clone;
          } else if (original instanceof cclegacy.Asset) {
            throw new TypeError(getError(6903));
          }
        }
        cclegacy.game._isCloning = true;
        clone = doInstantiate(original);
        cclegacy.game._isCloning = false;
        {
          updateChildrenForDeserialize(clone);
        }
        return clone;
      }
      function doInstantiate(obj, parent) {
        let clone;
        if (obj._iN$t) {
          clone = obj._iN$t;
        } else if (obj.constructor) {
          const Klass = obj.constructor;
          clone = new Klass();
        } else {
          clone = Object.create(null);
        }
        enumerateObject(obj, clone, parent);
        for (let i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
          objsToClearTmpVar[i]._iN$t = null;
        }
        objsToClearTmpVar.length = 0;
        return clone;
      }
      function enumerateCCClass(klass, obj, clone, parent) {
        const props = klass.__values__;
        for (let p = 0; p < props.length; p++) {
          const key = props[p];
          const value = obj[key];
          if (typeof value === 'object' && value) {
            const 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);
        const klass = obj.constructor;
        if (isCCClassOrFastDefined(klass)) {
          enumerateCCClass(klass, obj, clone, parent);
        } else {
          for (const key in obj) {
            if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__' && key !== '__prefab') {
              continue;
            }
            const value = obj[key];
            if (typeof value === 'object' && value) {
              if (value === clone) {
                continue;
              }
              clone[key] = value._iN$t || instantiateObj(value, parent);
            } else {
              clone[key] = value;
            }
          }
        }
        if (isCCObject(obj)) {
          clone._objFlags &= PersistentMask;
        }
      }
      function instantiateObj(obj, parent) {
        if (obj instanceof ValueType) {
          return obj.clone();
        }
        if (obj instanceof cclegacy.Asset) {
          return obj;
        }
        let clone;
        if (ArrayBuffer.isView(obj)) {
          const len = obj.length;
          clone = new obj.constructor(len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (let i = 0; i < len; ++i) {
            clone[i] = obj[i];
          }
          return clone;
        }
        if (Array.isArray(obj)) {
          const len = obj.length;
          clone = new Array(len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (let i = 0; i < len; ++i) {
            const 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;
        }
        const 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;
      cclegacy.instantiate = instantiate;

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

      var _dec$1w, _class$1w, _class2$1j, _initializer$1d, _dec2$19, _class4$j, _class5$i, _initializer2$10;
      const outgoingsSymbol = Symbol('[[Outgoing transitions]]');
      const incomingsSymbol = Symbol('[[Incoming transitions]]');
      const {
        ccclass: ccclass$D,
        serializable: serializable$h
      } = _decorator;
      let State = (_dec$1w = ccclass$D('cc.animation.State'), _dec$1w(_class$1w = (_class2$1j = class State extends EditorExtendable {
        constructor() {
          super();
          this.name = _initializer$1d && _initializer$1d();
          this[outgoingsSymbol] = [];
          this[incomingsSymbol] = [];
        }
        copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        }
      }, (_initializer$1d = applyDecoratedInitializer(_class2$1j.prototype, "name", [serializable$h], function () {
        return '';
      })), _class2$1j)) || _class$1w);
      let InteractiveState = (_dec2$19 = ccclass$D(`${CLASS_NAME_PREFIX_ANIM}InteractiveState`), _dec2$19(_class4$j = (_class5$i = class InteractiveState extends State {
        constructor(...args) {
          super(...args);
          this._components = _initializer2$10 && _initializer2$10();
        }
        get components() {
          return this._components;
        }
        addComponent(constructor) {
          const component = new constructor();
          this._components.push(component);
          return component;
        }
        removeComponent(component) {
          remove(this._components, component);
        }
        instantiateComponents() {
          const instantiatedComponents = this._components.map(component => {
            const instantiated = instantiate(component);
            return instantiated;
          });
          return instantiatedComponents;
        }
        copyTo(that) {
          super.copyTo(that);
          that._components = this.instantiateComponents();
        }
      }, (_initializer2$10 = applyDecoratedInitializer(_class5$i.prototype, "_components", [serializable$h], function () {
        return [];
      })), _class5$i)) || _class4$j);

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

      var _dec$1v, _class$1v, _class2$1i, _initializer$1c;
      let AnimationGraphEventBinding = (_dec$1v = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AnimationGraphEventBinding`), _dec$1v(_class$1v = (_class2$1i = class AnimationGraphEventBinding {
        constructor() {
          this.methodName = _initializer$1c && _initializer$1c();
        }
        get isBound() {
          return !!this.methodName;
        }
        emit(origin) {
          if (!this.methodName) {
            return;
          }
          invokeComponentMethodsEngagedInAnimationEvent(origin, this.methodName, []);
        }
        copyTo(that) {
          that.methodName = this.methodName;
          return this;
        }
      }, (_initializer$1c = applyDecoratedInitializer(_class2$1i.prototype, "methodName", [serializable$l], function () {
        return '';
      })), _class2$1i)) || _class$1v);

      var _dec$1u, _class$1u, _class2$1h, _initializer$1b, _initializer2$$, _initializer3$M, _initializer4$G, _initializer5$v, _initializer6$o;
      let MotionState = (_dec$1u = ccclass$H('cc.animation.Motion'), _dec$1u(_class$1u = (_class2$1h = class MotionState extends InteractiveState {
        constructor(...args) {
          super(...args);
          this.motion = _initializer$1b && _initializer$1b();
          this.speed = _initializer2$$ && _initializer2$$();
          this.speedMultiplier = _initializer3$M && _initializer3$M();
          this.speedMultiplierEnabled = _initializer4$G && _initializer4$G();
          this.transitionInEventBinding = _initializer5$v && _initializer5$v();
          this.transitionOutEventBinding = _initializer6$o && _initializer6$o();
        }
        __callOnAfterDeserializeRecursive() {
          var _this$motion;
          (_this$motion = this.motion) === null || _this$motion === void 0 ? void 0 : _this$motion.__callOnAfterDeserializeRecursive();
        }
        copyTo(that) {
          var _this$motion$clone, _this$motion2;
          super.copyTo(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;
        }
      }, (_initializer$1b = applyDecoratedInitializer(_class2$1h.prototype, "motion", [serializable$l], function () {
        return null;
      }), _initializer2$$ = applyDecoratedInitializer(_class2$1h.prototype, "speed", [serializable$l], function () {
        return 1.0;
      }), _initializer3$M = applyDecoratedInitializer(_class2$1h.prototype, "speedMultiplier", [serializable$l], function () {
        return '';
      }), _initializer4$G = applyDecoratedInitializer(_class2$1h.prototype, "speedMultiplierEnabled", [serializable$l], function () {
        return false;
      }), _initializer5$v = applyDecoratedInitializer(_class2$1h.prototype, "transitionInEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      }), _initializer6$o = applyDecoratedInitializer(_class2$1h.prototype, "transitionOutEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      })), _class2$1h)) || _class$1u);

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

      var _dec$1t, _class$1t;
      let AnimationGraphLike = (_dec$1t = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AnimationGraphLike`), _dec$1t(_class$1t = class AnimationGraphLike extends Asset {}) || _class$1t);

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

      var _dec$1s, _class$1s, _class2$1g, _initializer$1a, _dec2$18, _class4$i, _class5$h, _initializer2$_, _initializer3$L, _initializer4$F;
      let PoseGraphNodeShell = (_dec$1s = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseGraphNodeShell`), _dec$1s(_class$1s = (_class2$1g = class PoseGraphNodeShell extends EditorExtendable {
        constructor(...args) {
          super(...args);
          this._bindings = _initializer$1a && _initializer$1a();
        }
        getBindings() {
          return this._bindings;
        }
        addBinding(inputPath, producer, outputIndex) {
          this._emplaceBinding(new PoseGraphNodeInputBinding(inputPath, producer, outputIndex));
        }
        deleteBinding(inputPath) {
          const index = this._findBindingIndex(inputPath);
          if (index >= 0) {
            this._bindings.splice(index, 1);
          }
        }
        moveArrayElementBindingForward(propertyKey, firstIndex, forward) {
          const {
            _bindings: bindings
          } = this;
          const oldBindings = [];
          for (let iBinding = 0; iBinding < bindings.length; ++iBinding) {
            const binding = bindings[iBinding];
            const [consumerPropertyKey, consumerElementIndex = -1] = binding.inputPath;
            if (consumerPropertyKey === propertyKey && consumerElementIndex >= firstIndex) {
              oldBindings.push(binding);
              bindings.splice(iBinding, 1);
            }
          }
          for (const oldBinding of oldBindings) {
            const [consumerPropertyKey, consumerElementIndex = -1] = oldBinding.inputPath;
            this.addBinding([consumerPropertyKey, consumerElementIndex + (forward ? -1 : 1)], oldBinding.producer, oldBinding.outputIndex);
          }
        }
        deleteBindingTo(producer) {
          const {
            _bindings: bindings
          } = this;
          for (let iBinding = 0; iBinding < bindings.length; ++iBinding) {
            const binding = bindings[iBinding];
            if (binding.producer === producer) {
              bindings.splice(iBinding, 1);
            }
          }
        }
        findBinding(inputPath) {
          const bindingIndex = this._findBindingIndex(inputPath);
          return bindingIndex >= 0 ? this._bindings[bindingIndex] : undefined;
        }
        _findBindingIndex(inputPath) {
          return this._bindings.findIndex(searchElement => isEqualNodeInputPath(searchElement.inputPath, inputPath));
        }
        _emplaceBinding(binding) {
          const index = this._bindings.findIndex(searchElement => isEqualNodeInputPath(searchElement.inputPath, binding.inputPath));
          if (index >= 0) {
            this._bindings[index] = binding;
          } else {
            this._bindings.push(binding);
          }
        }
      }, (_initializer$1a = applyDecoratedInitializer(_class2$1g.prototype, "_bindings", [serializable$l], function () {
        return [];
      })), _class2$1g)) || _class$1s);
      function isEqualNodeInputPath(lhs, rhs) {
        const [lhsPropertyKey, lhsElementIndex] = lhs;
        const [rhsPropertyKey, rhsElementIndex] = rhs;
        return lhsPropertyKey === rhsPropertyKey && lhsElementIndex === rhsElementIndex;
      }
      let PoseGraphNodeInputBinding = (_dec2$18 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseGraphNodeInputBinding`), _dec2$18(_class4$i = (_class5$h = class PoseGraphNodeInputBinding {
        constructor(inputPath, producer, outputIndex) {
          this._inputPath = _initializer2$_ && _initializer2$_();
          this._producer = _initializer3$L && _initializer3$L();
          this._outputIndex = _initializer4$F && _initializer4$F();
          this._inputPath = inputPath;
          this._producer = producer;
          if (typeof outputIndex !== 'undefined') {
            this._outputIndex = outputIndex;
          }
        }
        get inputPath() {
          return this._inputPath;
        }
        get producer() {
          return this._producer;
        }
        get outputIndex() {
          return this._outputIndex;
        }
      }, (_initializer2$_ = applyDecoratedInitializer(_class5$h.prototype, "_inputPath", [serializable$l], null), _initializer3$L = applyDecoratedInitializer(_class5$h.prototype, "_producer", [serializable$l], null), _initializer4$F = applyDecoratedInitializer(_class5$h.prototype, "_outputIndex", [serializable$l], function () {
        return 0;
      })), _class5$h)) || _class4$i);

      class AddNonFreestandingNodeError extends Error {
        constructor(node) {
          super(`Can not add the specified ${node.toString()} since it has already been added into another graph.`);
        }
      }
      class OperationOnFreestandingNodeError extends Error {
        constructor(node) {
          super(`Can not perform specified operation on ${node.toString()} since it has not been added in to graph.`);
        }
      }

      class PoseGraphNode extends EditorExtendable {}

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

      function makeNodeEditorMetadataModifier(edit) {
        return target => {
          if (!checkDecoratingClass(target)) {
            return;
          }
          const metadata = getOrCreateNodeEditorMetadata(target);
          edit(metadata);
        };
      }
      const poseGraphNodeCategory = category => makeNodeEditorMetadataModifier(metadata => {
        metadata.category = category;
      });
      const poseGraphCreateNodeFactory = factory => makeNodeEditorMetadataModifier(metadata => {
        metadata.factory = factory;
      });
      const poseGraphNodeAppearance = appearance => makeNodeEditorMetadataModifier(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;
      }

      class PoseGraphNodeInputManager {
        constructor() {
          this._classInputMap = new WeakMap();
        }
        setPropertyNodeInputRecord(constructor, propertyKey, options) {
          let classInputRecord = this._classInputMap.get(constructor);
          if (!classInputRecord) {
            classInputRecord = {
              properties: {}
            };
            this._classInputMap.set(constructor, classInputRecord);
          }
          const {
            arraySyncGroup,
            ...unchanged
          } = options;
          const record = unchanged;
          const arraySyncGroupName = options.arraySyncGroup;
          if (arraySyncGroupName) {
            var _classInputRecord$arr, _classInputRecord$arr2;
            if (!classInputRecord.arraySyncGroups) {
              classInputRecord.arraySyncGroups = {};
            }
            const 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);
        }
        getInputKeys(object) {
          const result = [];
          const getInputKeysRecurse = constructor => {
            if (!constructor) {
              return;
            }
            getInputKeysRecurse(getSuper(constructor));
            const record = this._classInputMap.get(constructor);
            if (!record) {
              return;
            }
            for (const [propertyKey] of Object.entries(record.properties)) {
              if (result.findIndex(([subClassPropertyKey]) => propertyKey === subClassPropertyKey) >= 0) {
                continue;
              }
              const field = object[propertyKey];
              if (Array.isArray(field)) {
                for (let iElement = 0; iElement < field.length; ++iElement) {
                  result.push([propertyKey, iElement]);
                }
              } else {
                result.push([propertyKey]);
              }
            }
          };
          getInputKeysRecurse(object.constructor);
          return result;
        }
        isPoseInput(object, key) {
          const [propertyKey] = key;
          const propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return false;
          }
          return propertyInputRecord.type === 5;
        }
        getInputMetadata(object, key) {
          const [propertyKey, elementIndex = -1] = key;
          const propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return undefined;
          }
          const field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return undefined;
            } else {
              var _propertyInputRecord$, _propertyInputRecord$2;
              const 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,
                deletable: !(propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower),
                insertPoint: true
              };
            }
          }
          return {
            type: propertyInputRecord.type,
            displayName: propertyInputRecord.displayName
          };
        }
        hasInput(object, key) {
          const [propertyKey, elementIndex = -1] = key;
          const record = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!record) {
            return false;
          }
          const field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return false;
            }
          }
          return true;
        }
        getInputInsertInfos(object) {
          const result = {};
          for (let constructor = object.constructor; constructor; constructor = getSuper(constructor)) {
            const classInputRecord = this._classInputMap.get(constructor);
            if (!classInputRecord) {
              continue;
            }
            for (const propertyKey in classInputRecord.properties) {
              const propertyInputRecord = classInputRecord.properties[propertyKey];
              const property = object[propertyKey];
              if (Array.isArray(property)) {
                if (propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower) {
                  continue;
                }
                result[propertyKey] = {
                  displayName: propertyKey
                };
              }
            }
          }
          return result;
        }
        deleteInput(graph, node, key) {
          const [propertyKey, elementIndex = -1] = key;
          const propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          const property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          if (elementIndex < 0 || elementIndex >= property.length) {
            return;
          }
          {
            const {
              arraySyncGroup
            } = propertyInputRecord;
            if (arraySyncGroup) {
              this._deleteInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, elementIndex);
              return;
            }
          }
          deletePoseGraphNodeArrayElement(graph, node, key);
        }
        insertInput(graph, node, insertId) {
          const propertyKey = insertId;
          const propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          const property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          const hint = property.length;
          {
            const {
              arraySyncGroup
            } = propertyInputRecord;
            if (arraySyncGroup) {
              this._insertInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, hint);
              return;
            }
          }
          insertPoseGraphNodeArrayElement(graph, node, [propertyKey, hint], createDefaultInputValueByType(propertyInputRecord.type));
        }
        _getPropertyNodeInputRecord(constructor, propertyKey) {
          if (!constructor) {
            return undefined;
          }
          const classInputRecord = this._classInputMap.get(constructor);
          if (classInputRecord) {
            const record = classInputRecord.properties[propertyKey];
            if (record) {
              return record;
            }
          }
          return this._getPropertyNodeInputRecord(getSuper(constructor), propertyKey);
        }
        _insertInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, insertHint) {
          for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            const syncedPropertyKey = syncGroup.members[iGroupMember];
            const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            const syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            insertPoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, insertHint], createDefaultInputValueByType(syncedPropertyInputRecord.type));
          }
        }
        _deleteInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, index) {
          for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            const syncedPropertyKey = syncGroup.members[iGroupMember];
            const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            const syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            deletePoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, index]);
          }
        }
      }
      function insertPoseGraphNodeArrayElement(graph, node, inputKey, value) {
        const shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        const [propertyKey, elementIndex = -1] = inputKey;
        const property = node[propertyKey];
        if (!Array.isArray(property)) {
          return;
        }
        property.splice(elementIndex, 0, value);
        shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, false);
      }
      function deletePoseGraphNodeArrayElement(graph, node, inputKey) {
        const shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        const [propertyKey, elementIndex = -1] = inputKey;
        const 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 0:
          case 1:
            return 0;
          case 2:
            return false;
          case 5:
            return null;
          case 3:
            return new Vec3();
          case 4:
            return new Quat();
        }
      }
      const globalPoseGraphNodeInputManager = new PoseGraphNodeInputManager();

      var _dec$1r, _class$1r;
      const PoseTransformSpaceRequirement = {
        "NO": 0,
        "LOCAL": 1,
        "COMPONENT": 2
      };
      ccenum(PoseTransformSpaceRequirement);
      let PoseNode = (_dec$1r = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseNode`), _dec$1r(_class$1r = class PoseNode extends PoseGraphNode {
        constructor(...args) {
          super(...args);
          this._dependencyEvaluation = undefined;
        }
        update(context) {
          var _this$_dependencyEval;
          (_this$_dependencyEval = this._dependencyEvaluation) === null || _this$_dependencyEval === void 0 ? void 0 : _this$_dependencyEval.evaluate();
          this.doUpdate(context);
        }
        evaluate(context, poseTransformSpaceRequirement) {
          const pose = this.doEvaluate(context);
          const currentSpace = pose._poseTransformSpace;
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case 0:
              break;
            case 1:
              {
                if (currentSpace === 1) {
                  context._poseTransformsSpaceComponentToLocal(pose);
                }
                assertIsTrue(pose._poseTransformSpace === 0);
                break;
              }
            case 2:
              {
                if (currentSpace === 0) {
                  context._poseTransformsSpaceLocalToComponent(pose);
                }
                assertIsTrue(pose._poseTransformSpace === 1);
                break;
              }
          }
          return pose;
        }
        static evaluateDefaultPose(context, poseTransformSpaceRequirement) {
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case 0:
            case 1:
              return context.pushDefaultedPose();
            case 2:
              return context.pushDefaultedPoseInComponentSpace();
          }
        }
        _setDependencyEvaluation(dependency) {
          this._dependencyEvaluation = dependency;
        }
        _forceEvaluateEvaluation() {
          var _this$_dependencyEval2;
          (_this$_dependencyEval2 = this._dependencyEvaluation) === null || _this$_dependencyEval2 === void 0 ? void 0 : _this$_dependencyEval2.evaluate();
        }
      }) || _class$1r);

      class PureValueNode extends PoseGraphNode {
        constructor(outputTypes) {
          super();
          this._outputTypes = [];
          this._outputTypes = outputTypes;
        }
        get outputCount() {
          return this._outputTypes.length;
        }
        getOutputType(outputIndex) {
          return this._outputTypes[outputIndex];
        }
        link(context) {}
      }

      function input(options) {
        return (target, propertyKey) => {
          const targetConstructor = target.constructor;
          if (options.type === 5) {
            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 (target, propertyKey) => {
          if (typeof propertyKey !== 'string') {
            error(`@input can be only applied to string-named fields.`);
            return;
          }
          const targetConstructor = target.constructor;
          globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(targetConstructor, propertyKey, options);
          const propertyStash = getOrCreatePropertyStash(target, propertyKey);
          propertyStash.__internalFlags |= 1 | 2;
        };
      }

      var _dec$1q, _dec2$17, _dec3$R, _class$1q, _class2$1f, _descriptor$1;
      let PoseGraphOutputNode = (_dec$1q = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseGraphOutputNode`), _dec2$17 = poseGraphNodeAppearance({
        themeColor: '#CD3A58',
        inline: true
      }), _dec3$R = inputUnchecked({
        type: 5
      }), _dec$1q(_class$1q = _dec2$17(_class$1q = (_class2$1f = class PoseGraphOutputNode extends PoseGraphNode {
        constructor(...args) {
          super(...args);
          _initializerDefineProperty(this, "pose", _descriptor$1, this);
        }
      }, (_descriptor$1 = _applyDecoratedDescriptor(_class2$1f.prototype, "pose", [serializable$l, _dec3$R], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function () {
          return null;
        }
      })), _class2$1f)) || _class$1q) || _class$1q);

      var _dec$1p, _class$1p, _class2$1e, _initializer$19, _initializer2$Z, _initializer3$K, _initializer4$E;
      let PoseGraph = (_dec$1p = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseGraph`), _dec$1p(_class$1p = (_class2$1e = class PoseGraph extends EditorExtendable {
        constructor() {
          super();
          this._outputNode = _initializer$19 && _initializer$19();
          this._nodes = _initializer2$Z && _initializer2$Z();
          this._shells = _initializer3$K && _initializer3$K();
          this._shellMap = _initializer4$E && _initializer4$E();
          this.addNode(this._outputNode);
        }
        get outputNode() {
          return this._outputNode;
        }
        __callOnAfterDeserializeRecursive() {
          assertIsTrue(this._nodes.length === this._shells.length);
          for (let iNode = 0; iNode < this._nodes.length; ++iNode) {
            var _node$__callOnAfterDe;
            const node = this._nodes[iNode];
            const shell = this._shells[iNode];
            this._shellMap.set(node, shell);
            (_node$__callOnAfterDe = node.__callOnAfterDeserializeRecursive) === null || _node$__callOnAfterDe === void 0 ? void 0 : _node$__callOnAfterDe.call(node);
          }
        }
        nodes() {
          return this._nodes.values();
        }
        addNode(node) {
          if (this._shellMap.has(node)) {
            throw new AddNonFreestandingNodeError(node);
          }
          const shell = new PoseGraphNodeShell();
          this._shells.push(shell);
          this._nodes.push(node);
          this._shellMap.set(node, shell);
          return node;
        }
        removeNode(removal) {
          if (removal === this._outputNode) {
            error(`Can not remove the output node.`);
            return;
          }
          const nodeIndex = this._nodes.indexOf(removal);
          if (nodeIndex < 0) {
            return;
          }
          assertIsTrue(this._shellMap.has(removal));
          for (const shell of this._shells) {
            shell.deleteBindingTo(removal);
          }
          removeAt(this._shells, nodeIndex);
          removeAt(this._nodes, nodeIndex);
          this._shellMap.delete(removal);
        }
        getShell(node) {
          return this._shellMap.get(node);
        }
      }, (_initializer$19 = applyDecoratedInitializer(_class2$1e.prototype, "_outputNode", [serializable$l], function () {
        return new PoseGraphOutputNode();
      }), _initializer2$Z = applyDecoratedInitializer(_class2$1e.prototype, "_nodes", [serializable$l], function () {
        return [];
      }), _initializer3$K = applyDecoratedInitializer(_class2$1e.prototype, "_shells", [serializable$l], function () {
        return [];
      }), _initializer4$E = applyDecoratedInitializer(_class2$1e.prototype, "_shellMap", [serializable$l], function () {
        return new Map();
      })), _class2$1e)) || _class$1p);

      var _dec$1o, _class$1o, _class2$1d, _initializer$18, _initializer2$Y, _initializer3$J, _dec2$16, _class4$h, _class5$g, _initializer4$D, _initializer5$u, _initializer6$n, _initializer7$j, _dec3$Q, _class7$2, _class8$2, _initializer8$h, _initializer9$f, _initializer10$e, _initializer11$e, _dec4$B, _class10$1, _dec5$y, _class11$1, _class12$1, _initializer12$d, _dec6$q, _class14, _class15, _initializer13$a, _initializer14$8, _initializer15$6, _dec7$j, _class17, _class18, _initializer16$6, _dec8$c, _class20$1, _class21$1, _initializer17$3, _initializer18$3, _initializer19$2, _initializer20$2, _initializer21$2, _dec9$a, _class23, _class24, _initializer22$1, _dec10$4, _class26, _class27, _initializer23$1, _dec11$2, _class29, _class30, _initializer24$1, _initializer25$1, _initializer26$1, _initializer27$1, _initializer28$1, _initializer29$1, _dec12$2, _class32, _class33, _initializer30$1, _initializer31$1;
      let Transition$1 = (_dec$1o = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}Transition`), _dec$1o(_class$1o = (_class2$1d = class Transition extends EditorExtendable {
        constructor(from, to, conditions) {
          super();
          this.from = _initializer$18 && _initializer$18();
          this.to = _initializer2$Y && _initializer2$Y();
          this.conditions = _initializer3$J && _initializer3$J();
          this[ownerSymbol] = void 0;
          this.from = from;
          this.to = to;
          if (conditions) {
            this.conditions = conditions;
          }
        }
        copyTo(that) {
          that.conditions = this.conditions.map(condition => condition.clone());
        }
      }, (_initializer$18 = applyDecoratedInitializer(_class2$1d.prototype, "from", [serializable$l], null), _initializer2$Y = applyDecoratedInitializer(_class2$1d.prototype, "to", [serializable$l], null), _initializer3$J = applyDecoratedInitializer(_class2$1d.prototype, "conditions", [serializable$l], function () {
        return [];
      })), _class2$1d)) || _class$1o);
      let DurationalTransition = (_dec2$16 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}DurationalTransition`), _dec2$16(_class4$h = (_class5$g = class DurationalTransition extends Transition$1 {
        constructor(...args) {
          super(...args);
          this.destinationStart = _initializer4$D && _initializer4$D();
          this.relativeDestinationStart = _initializer5$u && _initializer5$u();
          this.startEventBinding = _initializer6$n && _initializer6$n();
          this.endEventBinding = _initializer7$j && _initializer7$j();
          this[ownerSymbol] = void 0;
        }
        copyTo(that) {
          super.copyTo(that);
          that.destinationStart = this.destinationStart;
          that.relativeDestinationStart = this.relativeDestinationStart;
          this.startEventBinding.copyTo(that.startEventBinding);
          this.endEventBinding.copyTo(that.endEventBinding);
        }
      }, (_initializer4$D = applyDecoratedInitializer(_class5$g.prototype, "destinationStart", [serializable$l], function () {
        return 0.0;
      }), _initializer5$u = applyDecoratedInitializer(_class5$g.prototype, "relativeDestinationStart", [serializable$l], function () {
        return false;
      }), _initializer6$n = applyDecoratedInitializer(_class5$g.prototype, "startEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      }), _initializer7$j = applyDecoratedInitializer(_class5$g.prototype, "endEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      })), _class5$g)) || _class4$h);
      let AnimationTransition = (_dec3$Q = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AnimationTransition`), _dec3$Q(_class7$2 = (_class8$2 = class AnimationTransition extends DurationalTransition {
        constructor(...args) {
          super(...args);
          this.duration = _initializer8$h && _initializer8$h();
          this.relativeDuration = _initializer9$f && _initializer9$f();
          this.exitConditionEnabled = _initializer10$e && _initializer10$e();
          this._exitCondition = _initializer11$e && _initializer11$e();
        }
        get exitCondition() {
          return this._exitCondition;
        }
        set exitCondition(value) {
          assertIsTrue(value >= 0.0);
          this._exitCondition = value;
        }
        copyTo(that) {
          super.copyTo(that);
          that.duration = this.duration;
          that.relativeDuration = this.relativeDuration;
          that.exitConditionEnabled = this.exitConditionEnabled;
          that.exitCondition = this.exitCondition;
        }
      }, (_initializer8$h = applyDecoratedInitializer(_class8$2.prototype, "duration", [serializable$l], function () {
        return 0.3;
      }), _initializer9$f = applyDecoratedInitializer(_class8$2.prototype, "relativeDuration", [serializable$l], function () {
        return false;
      }), _initializer10$e = applyDecoratedInitializer(_class8$2.prototype, "exitConditionEnabled", [serializable$l], function () {
        return true;
      }), _initializer11$e = applyDecoratedInitializer(_class8$2.prototype, "_exitCondition", [serializable$l], function () {
        return 1.0;
      })), _class8$2)) || _class7$2);
      function isAnimationTransition(transition) {
        return transition instanceof AnimationTransition;
      }
      let EmptyState = (_dec4$B = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}EmptyState`), _dec4$B(_class10$1 = class EmptyState extends State {}) || _class10$1);
      let EmptyStateTransition = (_dec5$y = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}EmptyStateTransition`), _dec5$y(_class11$1 = (_class12$1 = class EmptyStateTransition extends DurationalTransition {
        constructor(...args) {
          super(...args);
          this.duration = _initializer12$d && _initializer12$d();
        }
        copyTo(that) {
          super.copyTo(that);
          that.duration = this.duration;
        }
      }, (_initializer12$d = applyDecoratedInitializer(_class12$1.prototype, "duration", [serializable$l], function () {
        return 0.3;
      })), _class12$1)) || _class11$1);
      let ProceduralPoseState = (_dec6$q = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ProceduralPoseState`), _dec6$q(_class14 = (_class15 = class ProceduralPoseState extends State {
        constructor(...args) {
          super(...args);
          this.graph = _initializer13$a && _initializer13$a();
          this.transitionInEventBinding = _initializer14$8 && _initializer14$8();
          this.transitionOutEventBinding = _initializer15$6 && _initializer15$6();
        }
        __callOnAfterDeserializeRecursive() {
          this.graph.__callOnAfterDeserializeRecursive();
        }
        copyTo(that) {
          super.copyTo(that);
          this.transitionInEventBinding.copyTo(that.transitionInEventBinding);
          this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding);
          return this;
        }
      }, (_initializer13$a = applyDecoratedInitializer(_class15.prototype, "graph", [serializable$l], function () {
        return new PoseGraph();
      }), _initializer14$8 = applyDecoratedInitializer(_class15.prototype, "transitionInEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      }), _initializer15$6 = applyDecoratedInitializer(_class15.prototype, "transitionOutEventBinding", [serializable$l], function () {
        return new AnimationGraphEventBinding();
      })), _class15)) || _class14);
      const ProceduralPoseState_ = createInstanceofProxy(ProceduralPoseState);
      let ProceduralPoseTransition = (_dec7$j = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ProceduralPoseTransition`), _dec7$j(_class17 = (_class18 = class ProceduralPoseTransition extends DurationalTransition {
        constructor(...args) {
          super(...args);
          this.duration = _initializer16$6 && _initializer16$6();
        }
        copyTo(that) {
          super.copyTo(that);
          that.duration = this.duration;
        }
      }, (_initializer16$6 = applyDecoratedInitializer(_class18.prototype, "duration", [serializable$l], function () {
        return 0.3;
      })), _class18)) || _class17);
      const ProceduralPoseTransition_ = createInstanceofProxy(ProceduralPoseTransition);
      let StateMachine = (_dec8$c = ccclass$H('cc.animation.StateMachine'), _dec8$c(_class20$1 = (_class21$1 = class StateMachine extends EditorExtendable {
        __callOnAfterDeserializeRecursive() {
          this[onAfterDeserializedTag]();
          const nStates = this._states.length;
          for (let iState = 0; iState < nStates; ++iState) {
            const 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();
            }
          }
        }
        constructor(allowEmptyStates) {
          super();
          this._states = _initializer17$3 && _initializer17$3();
          this._transitions = _initializer18$3 && _initializer18$3();
          this._entryState = _initializer19$2 && _initializer19$2();
          this._exitState = _initializer20$2 && _initializer20$2();
          this._anyState = _initializer21$2 && _initializer21$2();
          this._allowEmptyStates = true;
          this._allowEmptyStates = allowEmptyStates !== null && allowEmptyStates !== void 0 ? allowEmptyStates : false;
          this._entryState = this._addState(new State());
          this._entryState.name = 'Entry';
          this._exitState = this._addState(new State());
          this._exitState.name = 'Exit';
          this._anyState = this._addState(new State());
          this._anyState.name = 'Any';
        }
        [onAfterDeserializedTag]() {
          this._states.forEach(state => own(state, this));
          this._transitions.forEach(transition => {
            transition.from[outgoingsSymbol].push(transition);
            transition.to[incomingsSymbol].push(transition);
          });
        }
        get allowEmptyStates() {
          return this._allowEmptyStates;
        }
        get entryState() {
          return this._entryState;
        }
        get exitState() {
          return this._exitState;
        }
        get anyState() {
          return this._anyState;
        }
        states() {
          return this._states;
        }
        transitions() {
          return this._transitions;
        }
        getTransitionsBetween(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          return from[outgoingsSymbol].filter(transition => transition.to === to);
        }
        getOutgoings(from) {
          assertsOwnedBy(from, this);
          return from[outgoingsSymbol];
        }
        getIncomings(to) {
          assertsOwnedBy(to, this);
          return to[incomingsSymbol];
        }
        addMotion() {
          return this._addState(new MotionState());
        }
        addSubStateMachine() {
          return this._addState(new SubStateMachine(this._allowEmptyStates));
        }
        addEmpty() {
          if (!this._allowEmptyStates) {
            throw new Error(`Empty states are now allowed in this state machine.`);
          }
          return this._addState(new EmptyState());
        }
        addProceduralPoseState() {
          return this._addState(new ProceduralPoseState());
        }
        remove(state) {
          assertsOwnedBy(state, this);
          if (state === this.entryState || state === this.exitState || state === this.anyState) {
            return;
          }
          this.eraseTransitionsIncludes(state);
          remove(this._states, state);
          markAsDangling(state);
        }
        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');
          }
          const 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;
        }
        disconnect(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          const oTransitions = from[outgoingsSymbol];
          const iTransitions = to[incomingsSymbol];
          const transitions = this._transitions;
          const oTransitionsToRemove = oTransitions.filter(oTransition => oTransition.to === to);
          const nOTransitionToRemove = oTransitionsToRemove.length;
          for (let iOTransitionToRemove = 0; iOTransitionToRemove < nOTransitionToRemove; ++iOTransitionToRemove) {
            const oTransition = oTransitionsToRemove[iOTransitionToRemove];
            remove(oTransitions, oTransition);
            assertIsTrue(remove(transitions, oTransition));
            assertIsNonNullable(removeIf(iTransitions, transition => transition === oTransition));
            markAsDangling(oTransition);
          }
        }
        removeTransition(removal) {
          assertIsTrue(remove(this._transitions, removal));
          assertIsNonNullable(removeIf(removal.from[outgoingsSymbol], transition => transition === removal));
          assertIsNonNullable(removeIf(removal.to[incomingsSymbol], transition => transition === removal));
          markAsDangling(removal);
        }
        eraseOutgoings(from) {
          assertsOwnedBy(from, this);
          const oTransitions = from[outgoingsSymbol];
          for (let iOTransition = 0; iOTransition < oTransitions.length; ++iOTransition) {
            const oTransition = oTransitions[iOTransition];
            const to = oTransition.to;
            assertIsTrue(remove(this._transitions, oTransition));
            assertIsNonNullable(removeIf(to[incomingsSymbol], transition => transition === oTransition));
            markAsDangling(oTransition);
          }
          oTransitions.length = 0;
        }
        eraseIncomings(to) {
          assertsOwnedBy(to, this);
          const iTransitions = to[incomingsSymbol];
          for (let iITransition = 0; iITransition < iTransitions.length; ++iITransition) {
            const iTransition = iTransitions[iITransition];
            const from = iTransition.from;
            assertIsTrue(remove(this._transitions, iTransition));
            assertIsNonNullable(removeIf(from[outgoingsSymbol], transition => transition === iTransition));
            markAsDangling(iTransition);
          }
          iTransitions.length = 0;
        }
        eraseTransitionsIncludes(state) {
          this.eraseIncomings(state);
          this.eraseOutgoings(state);
        }
        adjustTransitionPriority(adjusting, diff) {
          const {
            from
          } = adjusting;
          if (diff === 0) {
            return;
          }
          const outgoings = from[outgoingsSymbol];
          const iAdjusting = outgoings.indexOf(adjusting);
          assertIsTrue(iAdjusting >= 0);
          const iNew = clamp$1(iAdjusting + diff, 0, outgoings.length - 1);
          {
            const {
              _transitions: globalTransitions
            } = this;
            const adjustingIndexInGlobal = globalTransitions.indexOf(adjusting);
            assertIsTrue(adjustingIndexInGlobal >= 0);
            let lastPlaceholder = adjustingIndexInGlobal;
            if (iNew > iAdjusting) {
              for (let iOutgoing = iAdjusting + 1; iOutgoing <= iNew; ++iOutgoing) {
                const outgoing = outgoings[iOutgoing];
                const indexInGlobal = globalTransitions.indexOf(outgoing);
                assertIsTrue(indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = outgoing;
                lastPlaceholder = indexInGlobal;
              }
            } else if (iAdjusting > iNew) {
              for (let iOutgoing = iAdjusting - 1; iOutgoing >= iNew; --iOutgoing) {
                const outgoing = outgoings[iOutgoing];
                const indexInGlobal = globalTransitions.indexOf(outgoing);
                assertIsTrue(indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = outgoing;
                lastPlaceholder = indexInGlobal;
              }
            }
            globalTransitions[lastPlaceholder] = adjusting;
          }
          {
            shift(outgoings, iAdjusting, iNew);
          }
        }
        copyTo(that) {
          const thatStatesOld = that._states.filter(state => {
            switch (state) {
              case that._entryState:
              case that._exitState:
              case that._anyState:
                return true;
              default:
                return false;
            }
          });
          for (const thatStateOld of thatStatesOld) {
            that.remove(thatStateOld);
          }
          const stateMap = new Map();
          for (const state of this._states) {
            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;
                  }
                  const thatState = instantiate(state);
                  that._addState(thatState);
                  stateMap.set(state, thatState);
                } else {
                  assertIsTrue(false);
                }
                break;
            }
          }
          for (const transition of this._transitions) {
            if (!that._allowEmptyStates) {
              if (transition.from instanceof EmptyState || transition.to instanceof EmptyState) {
                continue;
              }
            }
            const thatFrom = stateMap.get(transition.from);
            const thatTo = stateMap.get(transition.to);
            assertIsTrue(thatFrom && thatTo);
            const thatTransition = that.connect(thatFrom, thatTo);
            thatTransition.conditions = transition.conditions.map(condition => 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);
            }
          }
        }
        clone() {
          const that = new StateMachine(this._allowEmptyStates);
          this.copyTo(that);
          return that;
        }
        _addState(state) {
          own(state, this);
          this._states.push(state);
          return state;
        }
      }, (_initializer17$3 = applyDecoratedInitializer(_class21$1.prototype, "_states", [serializable$l], function () {
        return [];
      }), _initializer18$3 = applyDecoratedInitializer(_class21$1.prototype, "_transitions", [serializable$l], function () {
        return [];
      }), _initializer19$2 = applyDecoratedInitializer(_class21$1.prototype, "_entryState", [serializable$l], null), _initializer20$2 = applyDecoratedInitializer(_class21$1.prototype, "_exitState", [serializable$l], null), _initializer21$2 = applyDecoratedInitializer(_class21$1.prototype, "_anyState", [serializable$l], null)), _class21$1)) || _class20$1);
      let SubStateMachine = (_dec9$a = ccclass$H('cc.animation.SubStateMachine'), _dec9$a(_class23 = (_class24 = class SubStateMachine extends InteractiveState {
        constructor(allowEmptyStates) {
          super();
          this._stateMachine = _initializer22$1 && _initializer22$1();
          this._stateMachine = new StateMachine(allowEmptyStates);
        }
        get stateMachine() {
          return this._stateMachine;
        }
        copyTo(that) {
          super.copyTo(that);
          this._stateMachine.copyTo(that._stateMachine);
        }
      }, (_initializer22$1 = applyDecoratedInitializer(_class24.prototype, "_stateMachine", [serializable$l], null)), _class24)) || _class23);
      let PoseGraphStash = (_dec10$4 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseGraphStash`), _dec10$4(_class26 = (_class27 = class PoseGraphStash extends EditorExtendable {
        constructor(...args) {
          super(...args);
          this.graph = _initializer23$1 && _initializer23$1();
        }
      }, (_initializer23$1 = applyDecoratedInitializer(_class27.prototype, "graph", [serializable$l], function () {
        return new PoseGraph();
      })), _class27)) || _class26);
      let Layer = (_dec11$2 = ccclass$H('cc.animation.Layer'), _dec11$2(_class29 = (_class30 = class Layer {
        __callOnAfterDeserializeRecursive() {
          this.stateMachine._allowEmptyStates = true;
          this.stateMachine.__callOnAfterDeserializeRecursive();
          for (const stashId in this._stashes) {
            const stash = this._stashes[stashId];
            stash.graph.__callOnAfterDeserializeRecursive();
          }
        }
        stashes() {
          return Object.entries(this._stashes);
        }
        getStash(id) {
          return this._stashes[id];
        }
        addStash(id) {
          return this._stashes[id] = new PoseGraphStash();
        }
        removeStash(id) {
          delete this._stashes[id];
        }
        renameStash(id, newId) {
          this._stashes = renameObjectProperty(this._stashes, id, newId);
        }
        constructor() {
          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);
        }
        get stateMachine() {
          return this._stateMachine;
        }
      }, (_initializer24$1 = applyDecoratedInitializer(_class30.prototype, "_stateMachine", [serializable$l], null), _initializer25$1 = applyDecoratedInitializer(_class30.prototype, "name", [serializable$l], function () {
        return '';
      }), _initializer26$1 = applyDecoratedInitializer(_class30.prototype, "weight", [serializable$l], function () {
        return 1.0;
      }), _initializer27$1 = applyDecoratedInitializer(_class30.prototype, "mask", [serializable$l], function () {
        return null;
      }), _initializer28$1 = applyDecoratedInitializer(_class30.prototype, "additive", [serializable$l], function () {
        return false;
      }), _initializer29$1 = applyDecoratedInitializer(_class30.prototype, "_stashes", [serializable$l], function () {
        return {};
      })), _class30)) || _class29);
      let AnimationGraph = (_dec12$2 = ccclass$H('cc.animation.AnimationGraph'), _dec12$2(_class32 = (_class33 = class AnimationGraph extends AnimationGraphLike {
        constructor() {
          super();
          this._layers = _initializer30$1 && _initializer30$1();
          this._variables = _initializer31$1 && _initializer31$1();
        }
        onLoaded() {
          const {
            _layers: layers
          } = this;
          const nLayers = layers.length;
          for (let iLayer = 0; iLayer < nLayers; ++iLayer) {
            layers[iLayer].__callOnAfterDeserializeRecursive();
          }
        }
        get layers() {
          return this._layers;
        }
        get variables() {
          return Object.entries(this._variables);
        }
        addLayer() {
          const layer = new Layer();
          this._layers.push(layer);
          return layer;
        }
        removeLayer(index) {
          removeAt(this._layers, index);
        }
        moveLayer(index, newIndex) {
          shift(this._layers, index, newIndex);
        }
        addVariable(name, type, initialValue) {
          const variable = createVariable(type, initialValue);
          this._variables[name] = variable;
          return variable;
        }
        removeVariable(name) {
          delete this._variables[name];
        }
        getVariable(name) {
          return this._variables[name];
        }
        renameVariable(name, newName) {
          this._variables = renameObjectProperty(this._variables, name, newName);
        }
      }, (_initializer30$1 = applyDecoratedInitializer(_class33.prototype, "_layers", [serializable$l], function () {
        return [];
      }), _initializer31$1 = applyDecoratedInitializer(_class33.prototype, "_variables", [serializable$l], function () {
        return {};
      })), _class33)) || _class32);

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

      var _dec$1n, _class$1n;
      let Motion = (_dec$1n = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}MotionBase`), _dec$1n(_class$1n = class Motion extends EditorExtendable {
        __callOnAfterDeserializeRecursive() {}
      }) || _class$1n);

      const BAKE_SKELETON_CURVE_SYMBOL = Symbol('BakeNodeCurves');

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

      class RatioSampler {
        constructor(ratios) {
          this.ratios = void 0;
          this._findRatio = void 0;
          this.ratios = ratios;
          let currRatioDif;
          let lastRatioDif;
          let canOptimize = true;
          const EPSILON = 1e-6;
          for (let 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;
        }
        sample(ratio) {
          return this._findRatio(this.ratios, ratio);
        }
      } exports("RatioSampler", RatioSampler);
      cclegacy.RatioSampler = RatioSampler;
      class AnimCurve {
        static Bezier(controlPoints) {
          return controlPoints;
        }
        constructor(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;
          const 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 (const index of Object.keys(propertyCurveData.easingMethods)) {
              this.types[index] = getCurveType(propertyCurveData.easingMethods[index]);
            }
          } else {
            this.type = null;
          }
          const firstValue = propertyCurveData.values[0];
          const interpolate = propertyCurveData.interpolate === undefined ? true : propertyCurveData.interpolate;
          if (interpolate) {
            this._lerp = selectLerpFx(firstValue);
          }
          if (propertyCurveData._arrayLength !== undefined) {
            this._array = new Array(propertyCurveData._arrayLength);
          }
        }
        hasLerp() {
          return !!this._lerp;
        }
        valueAt(index) {
          if (this._array === undefined) {
            const value = this._values[index];
            if (value && value.getNoLerp) {
              return value.getNoLerp();
            } else {
              return value;
            }
          } else {
            for (let i = 0; i < this._array.length; ++i) {
              this._array[i] = this._values[this._array.length * index + i];
            }
            return this._array;
          }
        }
        valueBetween(ratio, from, fromRatio, to, toRatio) {
          if (this._lerp) {
            const type = this.types ? this.types[from] : this.type;
            const dRatio = toRatio - fromRatio;
            let ratioBetweenFrames = (ratio - fromRatio) / dRatio;
            if (type) {
              ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type);
            }
            if (this._array === undefined) {
              const fromVal = this._values[from];
              const toVal = this._values[to];
              const value = this._lerp(fromVal, toVal, ratioBetweenFrames, dRatio * this._duration);
              return value;
            } else {
              for (let i = 0; i < this._array.length; ++i) {
                const fromVal = this._values[this._array.length * from + i];
                const 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 (let i = 0; i < this._array.length; ++i) {
              this._array[i] = this._values[this._array.length * from + i];
            }
            return this._array;
          }
        }
        empty() {
          return this._values.length === 0;
        }
        constant() {
          return this._values.length === 1;
        }
      } exports("AnimCurve", AnimCurve);
      AnimCurve.Linear = null;
      cclegacy.AnimCurve = AnimCurve;
      class EventInfo {
        constructor() {
          this.events = [];
        }
        add(func, params) {
          this.events.push({
            func: func || '',
            params: params || []
          });
        }
      } exports("EventInfo", EventInfo);
      function sampleAnimationCurve(curve, sampler, ratio) {
        let 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);
      }
      cclegacy.sampleAnimationCurve = sampleAnimationCurve;
      function computeRatioByType(ratio, type) {
        if (typeof type === 'string') {
          const 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) {
        const length = ratios.length - 1;
        if (length === 0) {
          return 0;
        }
        const start = ratios[0];
        if (ratio < start) {
          return 0;
        }
        const end = ratios[length];
        if (ratio > end) {
          return length;
        }
        ratio = (ratio - start) / (end - start);
        const eachLength = 1 / length;
        const index = ratio / eachLength;
        const floorIndex = index | 0;
        const EPSILON = 1e-6;
        if (index - floorIndex < EPSILON) {
          return floorIndex;
        } else if (floorIndex + 1 - index < EPSILON) {
          return floorIndex + 1;
        }
        return ~(floorIndex + 1);
      }
      const selectLerpFx = (() => {
        function makeValueTypeLerpFx(constructor) {
          const tempValue = new constructor();
          return (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() {
          const tempValue = new Quat();
          return (from, to, t, dt) => Quat.slerp(tempValue, from, to, t);
        }
        return 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$1m, _class2$1c, _initializer$17, _dec2$15, _class4$g, _class5$f, _initializer2$X;
      let UntypedTrackChannel = (_dec$1m = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}UntypedTrackChannel`), _dec$1m(_class$1m = (_class2$1c = class UntypedTrackChannel extends Channel {
        constructor() {
          super(new RealCurve());
          this.property = _initializer$17 && _initializer$17();
        }
      }, (_initializer$17 = applyDecoratedInitializer(_class2$1c.prototype, "property", [serializable$l], function () {
        return '';
      })), _class2$1c)) || _class$1m);
      let UntypedTrack = (_dec2$15 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}UntypedTrack`), _dec2$15(_class4$g = (_class5$f = class UntypedTrack extends Track {
        constructor(...args) {
          super(...args);
          this._channels = _initializer2$X && _initializer2$X();
        }
        channels() {
          return this._channels;
        }
        [createEvalSymbol]() {
          throw new Error(`UntypedTrack should be handled specially. Please file an issue.`);
        }
        createLegacyEval(hintValue) {
          const trySearchCurve = property => {
            var _this$_channels$find;
            return (_this$_channels$find = this._channels.find(channel => channel.property === property)) === null || _this$_channels$find === void 0 ? void 0 : _this$_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'));
          }
        }
        addChannel(property) {
          const channel = new UntypedTrackChannel();
          channel.property = property;
          this._channels.push(channel);
          return channel;
        }
        upgrade(refine) {
          const trySearchChannel = (property, outChannel) => {
            const untypedChannel = this.channels().find(channel => channel.property === property);
            if (untypedChannel) {
              outChannel.name = untypedChannel.name;
              outChannel.curve.assignSorted(Array.from(untypedChannel.curve.times()), Array.from(untypedChannel.curve.values()));
            }
          };
          const kind = refine(this.path, this.proxy);
          switch (kind) {
            default:
              break;
            case 'vec2':
            case 'vec3':
            case 'vec4':
              {
                const track = new VectorTrack();
                track.path = this.path;
                track.proxy = this.proxy;
                track.componentsCount = kind === 'vec2' ? 2 : kind === 'vec3' ? 3 : 4;
                const [x, y, z, w] = track.channels();
                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':
              {
                const track = new ColorTrack();
                const [r, g, b, a] = track.channels();
                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;
        }
      }, (_initializer2$X = applyDecoratedInitializer(_class5$f.prototype, "_channels", [serializable$l], function () {
        return [];
      })), _class5$f)) || _class4$g);

      class AnimationClipLegacyData {
        constructor(duration) {
          this._keys = [];
          this._curves = [];
          this._commonTargets = [];
          this._ratioSamplers = [];
          this._runtimeCurves = void 0;
          this._data = null;
          this._duration = void 0;
          this._duration = duration;
        }
        get keys() {
          return this._keys;
        }
        set keys(value) {
          this._keys = value;
        }
        get curves() {
          return this._curves;
        }
        set curves(value) {
          this._curves = value;
          delete this._runtimeCurves;
        }
        get commonTargets() {
          return this._commonTargets;
        }
        set commonTargets(value) {
          this._commonTargets = value;
        }
        get data() {
          return this._data;
        }
        getPropertyCurves() {
          if (!this._runtimeCurves) {
            this._createPropertyCurves();
          }
          return this._runtimeCurves;
        }
        toTracks() {
          const newTracks = [];
          const {
            keys: legacyKeys,
            curves: legacyCurves,
            commonTargets: legacyCommonTargets
          } = this;
          const convertTrackPath = (track, modifiers, valueAdapter) => {
            const trackPath = new TrackPath();
            for (const modifier of modifiers) {
              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;
          };
          const untypedTracks = legacyCommonTargets.map(legacyCommonTarget => {
            const track = new UntypedTrack();
            convertTrackPath(track, legacyCommonTarget.modifiers, legacyCommonTarget.valueAdapter);
            newTracks.push(track);
            return track;
          });
          for (const legacyCurve of legacyCurves) {
            var _legacyCurveData$inte;
            const legacyCurveData = legacyCurve.data;
            const legacyValues = legacyCurveData.values;
            if (legacyValues.length === 0) {
              continue;
            }
            const legacyKeysIndex = legacyCurveData.keys;
            const times = legacyKeysIndex < 0 ? [0.0] : legacyKeys[legacyCurveData.keys];
            const firstValue = legacyValues[0];
            const interpolate = (_legacyCurveData$inte = legacyCurveData.interpolate) !== null && _legacyCurveData$inte !== void 0 ? _legacyCurveData$inte : true;
            assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number');
            const legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length);
            const installPathAndSetter = track => {
              convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter);
            };
            let legacyCommonTargetCurve;
            if (typeof legacyCurve.commonTarget === 'number') {
              if (!legacyValues.every(value => typeof value === 'number')) {
                warnID(3932);
                continue;
              }
              if (legacyCurve.valueAdapter || legacyCurve.modifiers.length !== 1 || typeof legacyCurve.modifiers[0] !== 'string') {
                warnID(3933);
                continue;
              }
              const propertyName = legacyCurve.modifiers[0];
              const untypedTrack = untypedTracks[legacyCurve.commonTarget];
              const {
                curve
              } = untypedTrack.addChannel(propertyName);
              legacyCommonTargetCurve = curve;
            }
            const convertCurve = () => {
              if (typeof firstValue === 'number') {
                if (!legacyValues.every(value => typeof value === 'number')) {
                  warnID(3934);
                  return;
                }
                let realCurve;
                if (legacyCommonTargetCurve) {
                  realCurve = legacyCommonTargetCurve;
                } else {
                  const track = new RealTrack();
                  installPathAndSetter(track);
                  newTracks.push(track);
                  realCurve = track.channel.curve;
                }
                const interpolationMethod = interpolate ? 0 : 1;
                realCurve.assignSorted(times, legacyValues.map(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):
                    {
                      const components = firstValue instanceof Vec2 ? 2 : firstValue instanceof Vec3 ? 3 : 4;
                      const track = new VectorTrack();
                      installPathAndSetter(track);
                      track.componentsCount = components;
                      const [{
                        curve: x
                      }, {
                        curve: y
                      }, {
                        curve: z
                      }, {
                        curve: w
                      }] = track.channels();
                      const interpolationMode = interpolate ? 0 : 1;
                      const valueToFrame = value => ({
                        value,
                        interpolationMode
                      });
                      switch (components) {
                        case 4:
                          w.assignSorted(times, legacyValues.map(value => valueToFrame(value.w)));
                          legacyEasingMethodConverter.convert(w);
                        case 3:
                          z.assignSorted(times, legacyValues.map(value => valueToFrame(value.z)));
                          legacyEasingMethodConverter.convert(z);
                        default:
                          x.assignSorted(times, legacyValues.map(value => valueToFrame(value.x)));
                          legacyEasingMethodConverter.convert(x);
                          y.assignSorted(times, legacyValues.map(value => valueToFrame(value.y)));
                          legacyEasingMethodConverter.convert(y);
                          break;
                      }
                      newTracks.push(track);
                      return;
                    }
                  case everyInstanceOf(legacyValues, Quat):
                    {
                      const track = new QuatTrack();
                      installPathAndSetter(track);
                      const interpolationMode = interpolate ? 0 : 1;
                      track.channel.curve.assignSorted(times, legacyValues.map(value => ({
                        value: Quat.clone(value),
                        interpolationMode
                      })));
                      legacyEasingMethodConverter.convertQuatCurve(track.channel.curve);
                      newTracks.push(track);
                      return;
                    }
                  case everyInstanceOf(legacyValues, Color$1):
                    {
                      const track = new ColorTrack();
                      installPathAndSetter(track);
                      const [{
                        curve: r
                      }, {
                        curve: g
                      }, {
                        curve: b
                      }, {
                        curve: a
                      }] = track.channels();
                      const interpolationMode = interpolate ? 0 : 1;
                      const valueToFrame = value => ({
                        value,
                        interpolationMode
                      });
                      r.assignSorted(times, legacyValues.map(value => valueToFrame(value.r)));
                      legacyEasingMethodConverter.convert(r);
                      g.assignSorted(times, legacyValues.map(value => valueToFrame(value.g)));
                      legacyEasingMethodConverter.convert(g);
                      b.assignSorted(times, legacyValues.map(value => valueToFrame(value.b)));
                      legacyEasingMethodConverter.convert(b);
                      a.assignSorted(times, legacyValues.map(value => valueToFrame(value.a)));
                      legacyEasingMethodConverter.convert(a);
                      newTracks.push(track);
                      return;
                    }
                  case everyInstanceOf(legacyValues, Size$1):
                    {
                      const track = new SizeTrack();
                      installPathAndSetter(track);
                      const [{
                        curve: width
                      }, {
                        curve: height
                      }] = track.channels();
                      const interpolationMode = interpolate ? 0 : 1;
                      const valueToFrame = value => ({
                        value,
                        interpolationMode
                      });
                      width.assignSorted(times, legacyValues.map(value => valueToFrame(value.width)));
                      legacyEasingMethodConverter.convert(width);
                      height.assignSorted(times, legacyValues.map(value => valueToFrame(value.height)));
                      legacyEasingMethodConverter.convert(height);
                      newTracks.push(track);
                      return;
                    }
                  case everyInstanceOf(legacyValues, CubicSplineNumberValue):
                    {
                      assertIsTrue(legacyEasingMethodConverter.nil);
                      const track = new RealTrack();
                      installPathAndSetter(track);
                      const interpolationMode = interpolate ? 2 : 1;
                      track.channel.curve.assignSorted(times, legacyValues.map(value => ({
                        value: value.dataPoint,
                        leftTangent: value.inTangent,
                        rightTangent: value.outTangent,
                        interpolationMode
                      })));
                      newTracks.push(track);
                      return;
                    }
                  case everyInstanceOf(legacyValues, CubicSplineVec2Value):
                  case everyInstanceOf(legacyValues, CubicSplineVec3Value):
                  case everyInstanceOf(legacyValues, CubicSplineVec4Value):
                    {
                      assertIsTrue(legacyEasingMethodConverter.nil);
                      const components = firstValue instanceof CubicSplineVec2Value ? 2 : firstValue instanceof CubicSplineVec3Value ? 3 : 4;
                      const track = new VectorTrack();
                      installPathAndSetter(track);
                      track.componentsCount = components;
                      const [x, y, z, w] = track.channels();
                      const interpolationMode = interpolate ? 0 : 1;
                      const valueToFrame = (value, inTangent, outTangent) => ({
                        value,
                        leftTangent: inTangent,
                        rightTangent: outTangent,
                        interpolationMode
                      });
                      switch (components) {
                        case 4:
                          w.curve.assignSorted(times, legacyValues.map(value => valueToFrame(value.dataPoint.w, value.inTangent.w, value.outTangent.w)));
                        case 3:
                          z.curve.assignSorted(times, legacyValues.map(value => valueToFrame(value.dataPoint.z, value.inTangent.z, value.outTangent.z)));
                        default:
                          x.curve.assignSorted(times, legacyValues.map(value => valueToFrame(value.dataPoint.y, value.inTangent.y, value.outTangent.y)));
                          y.curve.assignSorted(times, legacyValues.map(value => valueToFrame(value.dataPoint.x, value.inTangent.x, value.outTangent.x)));
                          break;
                      }
                      newTracks.push(track);
                      return;
                    }
                  case legacyValues.every(value => value instanceof CubicSplineQuatValue):
                    {
                      warnID(3935);
                      break;
                    }
                }
              }
              const objectTrack = new ObjectTrack();
              installPathAndSetter(objectTrack);
              objectTrack.channel.curve.assignSorted(times, legacyValues);
              newTracks.push(objectTrack);
            };
            convertCurve();
          }
          return newTracks;
        }
        _createPropertyCurves() {
          this._ratioSamplers = this._keys.map(keys => new RatioSampler(keys.map(key => key / this._duration)));
          this._runtimeCurves = this._curves.map(targetCurve => ({
            curve: new AnimCurve(targetCurve.data, this._duration),
            modifiers: targetCurve.modifiers,
            valueAdapter: targetCurve.valueAdapter,
            sampler: this._ratioSamplers[targetCurve.data.keys],
            commonTarget: targetCurve.commonTarget
          }));
        }
      }
      function everyInstanceOf(array, constructor) {
        return array.every(element => element instanceof constructor);
      }
      class LegacyEasingMethodConverter {
        constructor(legacyCurveData, keyframesCount) {
          this._easingMethods = void 0;
          const {
            easingMethods
          } = legacyCurveData;
          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
            }, (_, index) => {
              var _easingMethods$index;
              return (_easingMethods$index = easingMethods[index]) !== null && _easingMethods$index !== void 0 ? _easingMethods$index : null;
            });
          }
        }
        get nil() {
          return !this._easingMethods || this._easingMethods.every(easingMethod => easingMethod === null || easingMethod === undefined);
        }
        convert(curve) {
          const {
            _easingMethods: easingMethods
          } = this;
          if (!easingMethods) {
            return;
          }
          const nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          const iLastKeyframe = nKeyframes - 1;
          for (let iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            const 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);
            }
          }
        }
        convertQuatCurve(curve) {
          const {
            _easingMethods: easingMethods
          } = this;
          if (!easingMethods) {
            return;
          }
          const nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          const iLastKeyframe = nKeyframes - 1;
          for (let iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            const easingMethod = easingMethods[iKeyframe];
            if (!easingMethod) {
              continue;
            }
            if (Array.isArray(easingMethod)) {
              curve.getKeyframeValue(iKeyframe).easingMethod = easingMethod.slice();
            } else {
              applyLegacyEasingMethodNameIntoQuatCurve(easingMethod, curve, iKeyframe);
            }
          }
        }
      }
      function applyLegacyEasingMethodName(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        const keyframeValue = curve.getKeyframeValue(keyframeIndex);
        const easingMethod = easingMethodNameMap[easingMethodName];
        if (easingMethod === 1) {
          keyframeValue.interpolationMode = 1;
        } else {
          keyframeValue.interpolationMode = 0;
          keyframeValue.easingMethod = easingMethod;
        }
      }
      function applyLegacyEasingMethodNameIntoQuatCurve(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        const keyframeValue = curve.getKeyframeValue(keyframeIndex);
        const easingMethod = easingMethodNameMap[easingMethodName];
        keyframeValue.easingMethod = easingMethod;
      }
      const easingMethodNameMap = {
        constant: 1,
        linear: 0,
        quadIn: 2,
        quadOut: 3,
        quadInOut: 4,
        quadOutIn: 5,
        cubicIn: 6,
        cubicOut: 7,
        cubicInOut: 8,
        cubicOutIn: 9,
        quartIn: 10,
        quartOut: 11,
        quartInOut: 12,
        quartOutIn: 13,
        quintIn: 14,
        quintOut: 15,
        quintInOut: 16,
        quintOutIn: 17,
        sineIn: 18,
        sineOut: 19,
        sineInOut: 20,
        sineOutIn: 21,
        expoIn: 22,
        expoOut: 23,
        expoInOut: 24,
        expoOutIn: 25,
        circIn: 26,
        circOut: 27,
        circInOut: 28,
        circOutIn: 29,
        elasticIn: 30,
        elasticOut: 31,
        elasticInOut: 32,
        elasticOutIn: 33,
        backIn: 34,
        backOut: 35,
        backInOut: 36,
        backOutIn: 37,
        bounceIn: 38,
        bounceOut: 39,
        bounceInOut: 40,
        bounceOutIn: 41,
        smooth: 42,
        fade: 43
      };
      function timeBezierToTangents(timeBezierPoints, previousTime, previousKeyframe, nextTime, nextKeyframe) {
        const [p1X, p1Y, p2X, p2Y] = timeBezierPoints;
        const {
          value: previousValue
        } = previousKeyframe;
        const {
          value: nextValue
        } = nextKeyframe;
        const dValue = nextValue - previousValue;
        const dTime = nextTime - previousTime;
        const fx = 3 * dTime;
        const fy = 3 * dValue;
        const t1x = p1X * fx;
        const t1y = p1Y * fy;
        const t2x = (1.0 - p2X) * fx;
        const t2y = (1.0 - p2Y) * fy;
        const ONE_THIRD = 1.0 / 3.0;
        const previousTangent = t1y / t1x;
        const previousTangentWeight = Math.sqrt(t1x * t1x + t1y * t1y) * ONE_THIRD;
        const nextTangent = t2y / t2x;
        const nextTangentWeight = Math.sqrt(t2x * t2x + t2y * t2y) * ONE_THIRD;
        previousKeyframe.interpolationMode = 2;
        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 === 0) {
          return 1;
        } else if (tangentWeightMode === 2) {
          return 3;
        } else {
          return tangentWeightMode;
        }
      }
      function ensureRightTangentWeightMode(tangentWeightMode) {
        if (tangentWeightMode === 0) {
          return 2;
        } else if (tangentWeightMode === 1) {
          return 3;
        } else {
          return tangentWeightMode;
        }
      }

      var _dec$1l, _class$1l, _class2$1b, _initializer$16, _dec2$14, _class4$f, _class5$e, _initializer2$W, _initializer3$I, _initializer4$C, _initializer5$t, _dec3$P, _class7$1, _class8$1, _initializer6$m, _initializer7$i, _dec4$A, _class10, _dec5$x, _class11, _dec6$p, _class12, _class13, _initializer8$g, _initializer9$e, _dec7$i, _class20, _class21, _initializer10$d, _initializer11$d, _initializer12$c, _initializer13$9;
      const {
        ccclass: ccclass$C,
        serializable: serializable$g
      } = _decorator;
      function throwIfSplitMethodIsNotValid() {
        throw new Error(`split() only valid in Editor.`);
      }
      (_dec$1l = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticAnimation`), _dec$1l(_class$1l = (_class2$1b = class ExoticAnimation {
        constructor() {
          this._nodeAnimations = _initializer$16 && _initializer$16();
        }
        createEvaluator(binder) {
          return new ExoticTrsAnimationEvaluator(this._nodeAnimations, binder);
        }
        createEvaluatorForAnimationGraph(context) {
          return new ExoticTrsAGEvaluation(this._nodeAnimations, context);
        }
        addNodeAnimation(path) {
          const nodeAnimation = new ExoticNodeAnimation(path);
          this._nodeAnimations.push(nodeAnimation);
          return nodeAnimation;
        }
        collectAnimatedJoints() {
          return Array.from(new Set(this._nodeAnimations.map(({
            path
          }) => path)));
        }
        split(from, to) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        }
        toHashString() {
          return this._nodeAnimations.map(nodeAnimation => nodeAnimation.toHashString()).join('\n');
        }
      }, (_initializer$16 = applyDecoratedInitializer(_class2$1b.prototype, "_nodeAnimations", [serializable$g], function () {
        return [];
      })), _class2$1b)) || _class$1l);
      let ExoticNodeAnimation = (_dec2$14 = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticNodeAnimation`), _dec2$14(_class4$f = (_class5$e = class ExoticNodeAnimation {
        constructor(path) {
          this._path = _initializer2$W && _initializer2$W();
          this._position = _initializer3$I && _initializer3$I();
          this._rotation = _initializer4$C && _initializer4$C();
          this._scale = _initializer5$t && _initializer5$t();
          this._path = path;
        }
        createPosition(times, values) {
          this._position = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        }
        createRotation(times, values) {
          this._rotation = new ExoticTrack(times, new ExoticQuatTrackValues(values));
        }
        createScale(times, values) {
          this._scale = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        }
        createEvaluator(binder) {
          return new ExoticNodeAnimationEvaluator(this._path, this._position, this._rotation, this._scale, binder);
        }
        createEvaluatorForAnimationGraph(context) {
          const transformHandle = context.bindTransform(this._path);
          if (!transformHandle) {
            return null;
          }
          return new ExoticNodeAnimationAGEvaluation(transformHandle, this._position, this._rotation, this._scale);
        }
        split(from, to, splitInfoCache) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        }
        get path() {
          return this._path;
        }
        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 : ''}`;
        }
      }, (_initializer2$W = applyDecoratedInitializer(_class5$e.prototype, "_path", [serializable$g], function () {
        return '';
      }), _initializer3$I = applyDecoratedInitializer(_class5$e.prototype, "_position", [serializable$g], function () {
        return null;
      }), _initializer4$C = applyDecoratedInitializer(_class5$e.prototype, "_rotation", [serializable$g], function () {
        return null;
      }), _initializer5$t = applyDecoratedInitializer(_class5$e.prototype, "_scale", [serializable$g], function () {
        return null;
      })), _class5$e)) || _class4$f);
      function floatToHashString(value) {
        return value.toPrecision(2);
      }
      function floatArrayToHashString(values) {
        return values.map(v => Number.parseFloat(floatToHashString(v))).join(' ');
      }
      let ExoticVectorLikeTrackValues = (_dec3$P = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticVectorLikeTrackValues`), _dec3$P(_class7$1 = (_class8$1 = class ExoticVectorLikeTrackValues {
        constructor(values) {
          this._values = _initializer6$m && _initializer6$m();
          this._isQuantized = _initializer7$i && _initializer7$i();
          this._values = values;
        }
        get precision() {
          return this._isQuantized ? this._values.originalPrecision : getFloatArrayPrecision(this._values);
        }
        quantize(type) {
          assertIsTrue(!this._isQuantized);
          this._values = quantize(this._values, type);
          this._isQuantized = true;
        }
        toHashString() {
          const {
            _isQuantized: isQuantized,
            _values: values
          } = this;
          return `${isQuantized} ${isQuantized ? values.toHashString() : floatArrayToHashString(values)}`;
        }
      }, (_initializer6$m = applyDecoratedInitializer(_class8$1.prototype, "_values", [serializable$g], null), _initializer7$i = applyDecoratedInitializer(_class8$1.prototype, "_isQuantized", [serializable$g], function () {
        return false;
      })), _class8$1)) || _class7$1);
      let ExoticVec3TrackValues = (_dec4$A = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticVec3TrackValues`), _dec4$A(_class10 = class ExoticVec3TrackValues extends ExoticVectorLikeTrackValues {
        static imitate(values, model) {
          const trackValues = new ExoticVec3TrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        }
        get(index, resultValue) {
          const {
            _values: values,
            _isQuantized: isQuantized
          } = this;
          if (isQuantized) {
            loadVec3FromQuantized(values, index, resultValue);
          } else {
            Vec3.fromArray(resultValue, values, index * 3);
          }
        }
        lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          const {
            _values: values,
            _isQuantized: isQuantized
          } = this;
          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);
        }
      }) || _class10);
      let ExoticQuatTrackValues = (_dec5$x = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticQuatTrackValues`), _dec5$x(_class11 = class ExoticQuatTrackValues extends ExoticVectorLikeTrackValues {
        static imitate(values, model) {
          const trackValues = new ExoticQuatTrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        }
        get(index, resultValue) {
          const {
            _values: values,
            _isQuantized: isQuantized
          } = this;
          if (isQuantized) {
            loadQuatFromQuantized(values, index, resultValue);
          } else {
            Quat.fromArray(resultValue, values, index * 4);
          }
        }
        lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          const {
            _values: values,
            _isQuantized: isQuantized
          } = this;
          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);
        }
      }) || _class11);
      let ExoticTrack = (_dec6$p = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}ExoticTrack`), _dec6$p(_class12 = (_class13 = class ExoticTrack {
        constructor(times, values) {
          this.times = _initializer8$g && _initializer8$g();
          this.values = _initializer9$e && _initializer9$e();
          this.times = times;
          this.values = values;
        }
        toHashString() {
          const {
            times,
            values
          } = this;
          return `times: ${floatArrayToHashString(times)}; values: ${values.toHashString()}`;
        }
      }, (_initializer8$g = applyDecoratedInitializer(_class13.prototype, "times", [serializable$g], null), _initializer9$e = applyDecoratedInitializer(_class13.prototype, "values", [serializable$g], null)), _class13)) || _class12);
      class ExoticTrsAnimationEvaluator {
        constructor(nodeAnimations, binder) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(nodeAnimation => nodeAnimation.createEvaluator(binder));
        }
        evaluate(time) {
          this._nodeEvaluations.forEach(nodeEvaluator => {
            nodeEvaluator.evaluate(time);
          });
        }
      }
      class ExoticNodeAnimationEvaluator {
        constructor(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);
          }
        }
        evaluate(time) {
          if (this._position) {
            const value = this._position.evaluator.evaluate(time);
            this._position.runtimeBinding.setValue(value);
          }
          if (this._rotation) {
            const value = this._rotation.evaluator.evaluate(time);
            this._rotation.runtimeBinding.setValue(value);
          }
          if (this._scale) {
            const value = this._scale.evaluator.evaluate(time);
            this._scale.runtimeBinding.setValue(value);
          }
        }
      }
      class ExoticTrackEvaluator {
        constructor(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();
        }
        evaluate(time) {
          const {
            _times: times,
            _values: values,
            _resultValue: resultValue
          } = this;
          const nFrames = times.length;
          if (nFrames === 0) {
            return resultValue;
          }
          const 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;
        }
      }
      class ExoticTrsAGEvaluation {
        constructor(nodeAnimations, context) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(nodeAnimation => nodeAnimation.createEvaluatorForAnimationGraph(context)).filter(x => !!x);
        }
        destroy() {
          const {
            _nodeEvaluations: nodeEvaluations
          } = this;
          const nNodeEvaluations = nodeEvaluations.length;
          for (let iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].destroy();
          }
        }
        evaluate(time, pose) {
          const {
            _nodeEvaluations: nodeEvaluations
          } = this;
          const nNodeEvaluations = nodeEvaluations.length;
          for (let iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
        }
      }
      class ExoticNodeAnimationAGEvaluation {
        constructor(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);
          }
        }
        destroy() {
          this._transformHandle.destroy();
        }
        evaluate(time, pose) {
          const {
            _transformHandle: {
              index: transformIndex
            },
            _position: position,
            _rotation: rotation,
            _scale: scale
          } = this;
          const {
            transforms: poseTransforms
          } = pose;
          if (position) {
            const value = position.evaluate(time);
            poseTransforms.setPosition(transformIndex, value);
          }
          if (rotation) {
            const rotationAbs = rotation.evaluate(time);
            poseTransforms.setRotation(transformIndex, rotationAbs);
          }
          if (scale) {
            const value = scale.evaluate(time);
            poseTransforms.setScale(transformIndex, value);
          }
        }
      }
      function sampleInput(values, time, result) {
        const nFrames = values.length;
        assertIsTrue(nFrames !== 0);
        const firstTime = values[0];
        const 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 {
          const index = binarySearchEpsilon(values, time);
          if (index >= 0) {
            result.just = true;
            result.index = index;
          } else {
            const nextIndex = ~index;
            assertIsTrue(nextIndex !== 0 && nextIndex !== nFrames && nFrames > 1);
            const prevIndex = nextIndex - 1;
            const prevTime = values[prevIndex];
            const nextTime = values[nextIndex];
            const ratio = (time - values[prevIndex]) / (nextTime - prevTime);
            result.just = false;
            result.index = prevIndex;
            result.nextIndex = nextIndex;
            result.ratio = ratio;
          }
        }
        return result;
      }
      const QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP = {
        uint8: Uint8Array,
        uint16: Uint16Array
      };
      function getFloatArrayPrecision(array) {
        switch (array.BYTES_PER_ELEMENT) {
          default:
            assertIsTrue(false);
          case 4:
            return 0;
          case 8:
            return 1;
        }
      }
      let QuantizedFloatArray = (_dec7$i = ccclass$C(`${CLASS_NAME_PREFIX_ANIM}QuantizedFloatArray`), _dec7$i(_class20 = (_class21 = class QuantizedFloatArray {
        get quantizationType() {
          switch (this.values.BYTES_PER_ELEMENT) {
            default:
            case 1:
              return 'uint8';
            case 2:
              return 'uint16';
          }
        }
        constructor(originalPrecision, values, extent, min = 0.0) {
          this.originalPrecision = _initializer10$d && _initializer10$d();
          this.min = _initializer11$d && _initializer11$d();
          this.extent = _initializer12$c && _initializer12$c();
          this.values = _initializer13$9 && _initializer13$9();
          this.originalPrecision = originalPrecision;
          this.values = values;
          this.extent = extent;
          this.min = min;
        }
        toHashString() {
          const {
            originalPrecision,
            min,
            extent,
            values
          } = this;
          return `${originalPrecision} ${floatToHashString(min)} ${floatToHashString(extent)} ${values.join(' ')}`;
        }
      }, (_initializer10$d = applyDecoratedInitializer(_class21.prototype, "originalPrecision", [serializable$g], null), _initializer11$d = applyDecoratedInitializer(_class21.prototype, "min", [serializable$g], null), _initializer12$c = applyDecoratedInitializer(_class21.prototype, "extent", [serializable$g], null), _initializer13$9 = applyDecoratedInitializer(_class21.prototype, "values", [serializable$g], null)), _class21)) || _class20);
      function quantize(values, type) {
        const TypedArrayViewConstructor = QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP[type];
        const MAX = 1 << TypedArrayViewConstructor.BYTES_PER_ELEMENT;
        let min = Number.POSITIVE_INFINITY;
        let max = Number.NEGATIVE_INFINITY;
        values.forEach(value => {
          min = Math.min(value, min);
          max = Math.max(value, max);
        });
        const extent = max - min;
        const normalized = TypedArrayViewConstructor.from(values, value => (value - min) / extent * MAX);
        return new QuantizedFloatArray(getFloatArrayPrecision(values), normalized, extent, min);
      }
      function indexQuantized(quantized, index) {
        const quantizedValue = quantized.values[index];
        const MAX_VALUE = 1 << quantized.values.BYTES_PER_ELEMENT;
        return quantizedValue / MAX_VALUE * quantized.extent + quantized.min;
      }
      function createExoticTrackEvaluationRecord(times, values, ValueConstructor, path, property, binder) {
        const trackBinding = new TrackBinding();
        trackBinding.path = new TrackPath().toHierarchy(path).toProperty(property);
        const runtimeBinding = binder(trackBinding);
        if (!runtimeBinding) {
          return null;
        }
        const evaluator = new ExoticTrackEvaluator(times, values, ValueConstructor);
        return {
          runtimeBinding,
          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$1k, _class2$1a, _initializer$15, _initializer2$V;
      let AuxiliaryCurveEntry = (_dec$1k = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AuxiliaryCurveEntry`), _dec$1k(_class$1k = (_class2$1a = class AuxiliaryCurveEntry {
        constructor() {
          this.name = _initializer$15 && _initializer$15();
          this.curve = _initializer2$V && _initializer2$V();
        }
      }, (_initializer$15 = applyDecoratedInitializer(_class2$1a.prototype, "name", [serializable$l], function () {
        return '';
      }), _initializer2$V = applyDecoratedInitializer(_class2$1a.prototype, "curve", [serializable$l], function () {
        return new RealCurve();
      })), _class2$1a)) || _class$1k);

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

      var _class$1i;
      const CACHE_VECTOR_A = new Vec3();
      const CACHE_VECTOR_B = new Vec3();
      const CACHE_QUAT_A = new Quat();
      new Quat();
      let Transform$1 = class Transform {
        constructor() {
          this._position = new Vec3();
          this._rotation = new Quat();
          this._scale = Vec3.clone(Vec3.ONE);
        }
        get position() {
          return this._position;
        }
        set position(value) {
          Vec3.copy(this._position, value);
        }
        get rotation() {
          return this._rotation;
        }
        set rotation(value) {
          Quat.copy(this._rotation, value);
        }
        get scale() {
          return this._scale;
        }
        set scale(value) {
          Vec3.copy(this._scale, value);
        }
        static clone(src) {
          const transform = new Transform();
          Transform.copy(transform, src);
          return transform;
        }
        static setIdentity(out) {
          Vec3.copy(out._position, Vec3.ZERO);
          Quat.copy(out._rotation, Quat.IDENTITY);
          Vec3.copy(out._scale, Vec3.ONE);
          return out;
        }
        static copy(out, src) {
          Vec3.copy(out._position, src._position);
          Quat.copy(out._rotation, src._rotation);
          Vec3.copy(out._scale, src._scale);
          return out;
        }
        static 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);
        }
        static strictEquals(a, b) {
          return Vec3.strictEquals(a._position, b._position) && Quat.strictEquals(a._rotation, b._rotation) && Vec3.strictEquals(a._scale, b._scale);
        }
        static 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;
        }
        static multiply(out, second, first) {
          const cacheRotation = Quat.multiply(CACHE_QUAT_A, second._rotation, first._rotation);
          const cacheScale = Vec3.multiply(CACHE_VECTOR_A, first._scale, second._scale);
          const 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;
        }
        static invert(out, transform) {
          const {
            _rotation: invRotation,
            _scale: invScale,
            _position: invPosition
          } = out;
          Quat.invert(invRotation, transform._rotation);
          invScaleOrZero(invScale, transform._scale, EPSILON$2);
          Vec3.negate(invPosition, transform._position);
          Vec3.multiply(invPosition, invPosition, invScale);
          Vec3.transformQuat(invPosition, invPosition, invRotation);
          return out;
        }
        static fromMatrix(out, matrix) {
          Mat4.toSRT(matrix, out._rotation, out._position, out._scale);
          return out;
        }
        static toMatrix(out, transform) {
          return Mat4.fromSRT(out, transform._rotation, transform._position, transform._scale);
        }
      };
      _class$1i = Transform$1;
      Transform$1.IDENTITY = Object.freeze(new _class$1i());
      Transform$1.ZERO = Object.freeze((() => {
        const transform = new _class$1i();
        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$1.calculateRelative = (() => {
        const cacheInvRotation = new Quat();
        const cacheInvScale = new Vec3();
        return (out, first, second) => {
          const invSecondRotation = Quat.invert(cacheInvRotation, second._rotation);
          const invScale = invScaleOrZero(cacheInvScale, second._scale, EPSILON$2);
          const 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) {
        const {
          x,
          y,
          z
        } = scale;
        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;
      }
      const __applyDeltaTransform = (() => {
        const cacheQuat = new Quat();
        return (out, base, delta, alpha) => {
          Vec3.scaleAndAdd(out.position, base.position, delta.position, alpha);
          const 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;
        };
      })();
      const deltaQuat = (() => {
        const quatMultiInvInverseCache = new Quat();
        return (out, from, to) => {
          const fromInv = Quat.invert(quatMultiInvInverseCache, from);
          return Quat.multiply(out, to, fromInv);
        };
      })();
      const ZERO_DELTA_TRANSFORM = Object.freeze((() => {
        const transform = new Transform$1();
        transform.position = Vec3.ZERO;
        transform.rotation = Quat.IDENTITY;
        transform.scale = Vec3.ZERO;
        return transform;
      })());

      class Pose {
        constructor(transforms, auxiliaryCurves) {
          this.transforms = void 0;
          this.auxiliaryCurves = void 0;
          this._poseTransformSpace = 0;
          this.transforms = transforms;
          this.auxiliaryCurves = auxiliaryCurves;
        }
        static _create(transforms, auxiliaryCurves) {
          return new Pose(transforms, auxiliaryCurves);
        }
      }
      class TransformFilter {
        constructor(involvedTransforms) {
          {
            assertIsTrue(involvedTransforms.every(transformIndex => transformIndex < 2 ** 16), 'The number of transforms exceeds the max allowed(2 ** 16)');
          }
          this._involvedTransforms = new Uint16Array(involvedTransforms);
        }
        get involvedTransforms() {
          return this._involvedTransforms;
        }
      }
      function blendPoseInto(target, source, alpha, transformFilter = undefined) {
        blendTransformsInto(target.transforms, source.transforms, alpha, transformFilter);
        blendAuxiliaryCurvesInto(target.auxiliaryCurves, source.auxiliaryCurves, alpha);
      }
      function blendTransformsInto(target, source, alpha, transformFilter = undefined) {
        const 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 (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
            blendIntoTransformArrayAt(target, source, alpha, iTransform);
          }
        } else {
          for (let index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            const involvedTransformIndex = transformFilter.involvedTransforms[index];
            blendIntoTransformArrayAt(target, source, alpha, involvedTransformIndex);
          }
        }
      }
      function copyTransformsWithFilter(target, source, filter) {
        const nTransforms = target.length;
        assertIsTrue(nTransforms === target.length);
        for (let index = 0; index < filter.involvedTransforms.length; ++index) {
          const involvedTransformIndex = filter.involvedTransforms[index];
          target.copyRange(involvedTransformIndex, source, involvedTransformIndex, 1);
        }
      }
      const blendIntoTransformArrayAt = (() => {
        const cacheTransformSource = new Transform$1();
        const cacheTransformTarget = new Transform$1();
        return (target, source, alpha, transformIndex) => {
          const transformTarget = target.getTransform(transformIndex, cacheTransformTarget);
          const transformSource = source.getTransform(transformIndex, cacheTransformSource);
          Transform$1.lerp(transformTarget, transformTarget, transformSource, alpha);
          target.setTransform(transformIndex, transformTarget);
        };
      })();
      function blendAuxiliaryCurvesInto(target, source, alpha) {
        const nValues = source.length;
        assertIsTrue(nValues === target.length);
        for (let 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);
      }
      const calculateDeltaTransformArrayAt = (() => {
        const cacheTransformBase = new Transform$1();
        const cacheTransformTarget = new Transform$1();
        return (target, base, transformIndex) => {
          const baseTransform = base.getTransform(transformIndex, cacheTransformBase);
          const targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __calculateDeltaTransform(targetTransform, targetTransform, baseTransform);
          target.setTransform(transformIndex, targetTransform);
        };
      })();
      function calculateDeltaTransforms(target, base) {
        const nTransforms = target.length;
        assertIsTrue(nTransforms === base.length);
        for (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
          calculateDeltaTransformArrayAt(target, base, iTransform);
        }
      }
      function calculateDeltaAuxiliaryCurves(target, base) {
        const nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === base.length);
        for (let i = 0; i < target.length; ++i) {
          target[i] -= base[i];
        }
      }
      function applyDeltaPose(target, base, alpha, transformFilter = undefined) {
        applyDeltaTransforms(target.transforms, base.transforms, alpha, transformFilter);
        applyDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves, alpha);
      }
      const applyDeltaTransformArrayAt = (() => {
        const cacheTransformDelta = new Transform$1();
        const cacheTransformTarget = new Transform$1();
        return (target, delta, alpha, transformIndex) => {
          const deltaTransform = delta.getTransform(transformIndex, cacheTransformDelta);
          const targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __applyDeltaTransform(targetTransform, targetTransform, deltaTransform, alpha);
          target.setTransform(transformIndex, targetTransform);
        };
      })();
      function applyDeltaTransforms(target, delta, alpha, transformFilter = undefined) {
        const nTransforms = target.length;
        assertIsTrue(nTransforms === delta.length);
        if (!transformFilter) {
          for (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
            applyDeltaTransformArrayAt(target, delta, alpha, iTransform);
          }
        } else {
          for (let index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            const transformIndex = transformFilter.involvedTransforms[index];
            applyDeltaTransformArrayAt(target, delta, alpha, transformIndex);
          }
        }
      }
      function applyDeltaAuxiliaryCurves(target, delta, alpha) {
        const nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === delta.length);
        for (let i = 0; i < target.length; ++i) {
          target[i] += delta[i] * alpha;
        }
      }

      const CACHE_VEC3_GET_VALUE = new Vec3();
      const CACHE_QUAT_GET_VALUE = new Quat();
      class PoseBindingBase {
        constructor(transformHandle) {
          this._transformHandle = transformHandle;
        }
        destroy() {
          this._transformHandle.destroy();
        }
      }
      class PosePositionBinding extends PoseBindingBase {
        setValue(value, pose) {
          pose.transforms.setPosition(this._transformHandle.index, value);
        }
        getValue(pose) {
          return pose.transforms.getPosition(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        }
      }
      class PoseRotationBinding extends PoseBindingBase {
        setValue(value, pose) {
          pose.transforms.setRotation(this._transformHandle.index, value);
        }
        getValue(pose) {
          return pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
        }
      }
      class PoseEulerAnglesBinding extends PoseBindingBase {
        setValue(value, pose) {
          const quat = Quat.fromEuler(PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE, value.x, value.y, value.z);
          pose.transforms.setRotation(this._transformHandle.index, quat);
        }
        getValue(pose) {
          const q = pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
          return Quat.toEuler(CACHE_VEC3_GET_VALUE, q);
        }
      }
      PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE = new Quat();
      class PoseScaleBinding extends PoseBindingBase {
        setValue(value, pose) {
          pose.transforms.setScale(this._transformHandle.index, value);
        }
        getValue(pose) {
          return pose.transforms.getScale(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        }
      }
      class AuxiliaryCurveBinding {
        constructor(_handle) {
          this._handle = _handle;
        }
        destroy() {
          this._handle.destroy();
        }
        setValue(value, pose) {
          pose.auxiliaryCurves[this._handle.index] = value;
        }
        getValue(pose) {
          return pose.auxiliaryCurves[this._handle.index];
        }
      }
      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);
        }
      }
      class NonTransformPoseBinding {
        constructor(binding) {
          this.binding = binding;
        }
        destroy() {}
        setValue(value, _pose) {
          this.binding.setValue(value);
        }
        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;
        }
      }
      class AGTrackEvaluation {
        constructor(binding, trackEvaluation) {
          this._binding = void 0;
          this._trackSampler = void 0;
          this._binding = binding;
          this._trackSampler = trackEvaluation;
        }
        destroy() {
          this._binding.destroy();
        }
        evaluate(time, pose) {
          const {
            _trackSampler: trackSampler,
            _binding: binding
          } = this;
          const defaultValue = trackSampler.requiresDefault ? binding.getValue(pose) : undefined;
          const value = trackSampler.evaluate(time, defaultValue);
          binding.setValue(value, pose);
        }
      }
      function bindTrackAG(animationClip, track, bindContext) {
        const trackBinding = track[trackBindingTag];
        const 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) {
        const {
          origin
        } = bindContext;
        const {
          path,
          proxy
        } = track;
        const nPaths = path.length;
        const iLastPath = nPaths - 1;
        if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
          const lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
          const resultTarget = path[normalizedFollowTag](origin, 0, nPaths - 1);
          if (resultTarget === null) {
            return null;
          }
          if (resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
            const transformPath = (() => {
              const segments = [];
              let 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') {
              const transformHandle = bindContext.bindTransform(transformPath);
              if (!transformHandle) {
                return undefined;
              }
              return bindPoseTransform(transformHandle, lastPropertyKey);
            }
          }
        }
        {
          const nonTransformBinding = track.createRuntimeBinding(bindContext.origin, undefined, false);
          if (!nonTransformBinding) {
            return null;
          }
          return new NonTransformPoseBinding(nonTransformBinding);
        }
      }
      class AuxiliaryCurveEvaluation {
        constructor(_binding, _curve) {
          this._binding = _binding;
          this._curve = _curve;
        }
        evaluate(time, context) {
          const {
            _curve: curve,
            _binding: binding
          } = this;
          const pose = context;
          const value = curve.evaluate(time);
          binding.setValue(value, pose);
        }
      }
      function createAnimationAGEvaluation(clip, context) {
        if (clip.isAdditive_experimental) {
          return new AnimationClipAGEvaluationAdditive(clip, context);
        } else {
          return new AnimationClipAGEvaluationRegular(clip, context);
        }
      }
      class AnimationClipAGEvaluationRegular {
        constructor(clip, context) {
          this._trackEvaluations = [];
          this._exoticAnimationEvaluation = void 0;
          this._auxiliaryCurveEvaluations = [];
          clip._trySyncLegacyData();
          const trackEvaluations = [];
          let exoticAnimationEvaluation;
          const auxiliaryCurveEvaluations = [];
          const {
            tracks
          } = clip;
          const exoticAnimation = clip[exoticAnimationTag];
          for (const track of tracks) {
            if (track instanceof UntypedTrack) {
              continue;
            }
            if (Array.from(track.channels()).every(({
              curve
            }) => curve.keyFramesCount === 0)) {
              continue;
            }
            const trackRuntimeBinding = bindTrackAG(clip, track, context);
            if (!trackRuntimeBinding) {
              continue;
            }
            const trackSampler = track[createEvalSymbol]();
            const trackEvaluation = new AGTrackEvaluation(trackRuntimeBinding, trackSampler);
            trackEvaluations.push(trackEvaluation);
          }
          if (exoticAnimation) {
            exoticAnimationEvaluation = exoticAnimation.createEvaluatorForAnimationGraph(context);
          }
          const auxiliaryCurveNames = clip.getAuxiliaryCurveNames_experimental();
          const nAuxiliaryCurves = auxiliaryCurveNames.length;
          for (let iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            const curveName = auxiliaryCurveNames[iAuxiliaryCurve];
            const curve = clip.getAuxiliaryCurve_experimental(curveName);
            const handle = context.bindAuxiliaryCurve(curveName);
            const binding = new AuxiliaryCurveBinding(handle);
            auxiliaryCurveEvaluations.push(new AuxiliaryCurveEvaluation(binding, curve));
          }
          this._trackEvaluations = trackEvaluations;
          this._exoticAnimationEvaluation = exoticAnimationEvaluation;
          this._auxiliaryCurveEvaluations = auxiliaryCurveEvaluations;
        }
        destroy() {
          var _this$_exoticAnimatio;
          (_this$_exoticAnimatio = this._exoticAnimationEvaluation) === null || _this$_exoticAnimatio === void 0 ? void 0 : _this$_exoticAnimatio.destroy();
          const {
            _trackEvaluations: trackEvaluations
          } = this;
          const nTrackEvaluations = trackEvaluations.length;
          for (let iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].destroy();
          }
        }
        evaluate(time, context) {
          const {
            _trackEvaluations: trackEvaluations,
            _exoticAnimationEvaluation: exoticAnimationEvaluation,
            _auxiliaryCurveEvaluations: auxiliaryCurveEvaluations
          } = this;
          const pose = context.pushDefaultedPose();
          const nTrackEvaluations = trackEvaluations.length;
          for (let iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
          if (exoticAnimationEvaluation) {
            exoticAnimationEvaluation.evaluate(time, pose);
          }
          const nAuxiliaryCurveEvaluations = auxiliaryCurveEvaluations.length;
          for (let iAuxiliaryCurveEvaluation = 0; iAuxiliaryCurveEvaluation < nAuxiliaryCurveEvaluations; ++iAuxiliaryCurveEvaluation) {
            auxiliaryCurveEvaluations[iAuxiliaryCurveEvaluation].evaluate(time, pose);
          }
          return pose;
        }
      }
      class AnimationClipAGEvaluationAdditive {
        constructor(clip, context) {
          this._clipEval = void 0;
          this._refClipEval = void 0;
          this._clipEval = new AnimationClipAGEvaluationRegular(clip, context);
          const refClip = clip[additiveSettingsTag].refClip;
          if (refClip && refClip !== clip) {
            this._refClipEval = new AnimationClipAGEvaluationRegular(refClip, context);
          }
        }
        destroy() {
          var _this$_refClipEval;
          this._clipEval.destroy();
          (_this$_refClipEval = this._refClipEval) === null || _this$_refClipEval === void 0 ? void 0 : _this$_refClipEval.destroy();
        }
        evaluate(time, context) {
          const pose = this._clipEval.evaluate(time, context);
          let refPose;
          if (this._refClipEval) {
            const refClipTime = 0.0;
            refPose = this._refClipEval.evaluate(refClipTime, context);
          } else {
            refPose = this._clipEval.evaluate(0.0, context);
          }
          calculateDeltaPose(pose, refPose);
          context.popPose();
          return pose;
        }
      }

      var _dec$1i, _dec2$12, _class$1h, _class2$18, _initializer$13;
      const {
        ccclass: ccclass$B,
        type: type$7
      } = _decorator;
      let ClipMotion = (_dec$1i = ccclass$B('cc.animation.ClipMotion'), _dec2$12 = type$7(AnimationClip), _dec$1i(_class$1h = (_class2$18 = class ClipMotion extends Motion {
        constructor(...args) {
          super(...args);
          this.clip = _initializer$13 && _initializer$13();
        }
        [createEval](context, ignoreEmbeddedPlayers) {
          if (!this.clip) {
            return null;
          }
          const clipMotionEval = new ClipMotionEval(context, this.clip, ignoreEmbeddedPlayers);
          return clipMotionEval;
        }
        clone() {
          const that = new ClipMotion();
          that.clip = this.clip;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
          return that;
        }
      }, (_initializer$13 = applyDecoratedInitializer(_class2$18.prototype, "clip", [_dec2$12, serializable$l], function () {
        return null;
      })), _class2$18)) || _class$1h);
      const evaluatePortTag = Symbol('EvaluatePort');
      class ClipMotionEval {
        constructor(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;
          const 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);
        }
        get duration() {
          return this._duration;
        }
        createPort() {
          return new ClipMotionPort(this);
        }
        getClipStatuses(baseWeight) {
          let got = false;
          return {
            next: () => {
              if (got) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                got = true;
                return {
                  done: false,
                  value: {
                    __DEBUG_ID__: this.__DEBUG__ID__,
                    clip: this._clip,
                    weight: baseWeight
                  }
                };
              }
            }
          };
        }
        [evaluatePortTag](progress, context) {
          var _this$_frameEventEval, _this$_clipEmbeddedPl;
          const {
            _duration: duration,
            _clip: {
              duration: clipDuration
            },
            _clipEval: clipEval
          } = this;
          const elapsedTime = duration * progress;
          const {
            wrapMode
          } = this._clip;
          const repeatCount = (wrapMode & 2) === 2 ? Infinity : 1;
          const wrapInfo = wrap(elapsedTime, duration, wrapMode, repeatCount, false, this._wrapInfo);
          const clipTime = wrapInfo.ratio * clipDuration;
          const 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;
        }
        overrideClips(context) {
          var _context$clipOverride3;
          const {
            _originalClip: originalClip
          } = this;
          const overriding = (_context$clipOverride3 = context.clipOverrides) === null || _context$clipOverride3 === void 0 ? void 0 : _context$clipOverride3.get(originalClip);
          if (overriding) {
            this._setClip(overriding, context);
          }
        }
        reenter() {
          var _this$_frameEventEval2;
          (_this$_frameEventEval2 = this._frameEventEval) === null || _this$_frameEventEval2 === void 0 ? void 0 : _this$_frameEventEval2.reset();
        }
        _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);
          }
        }
      }
      class ClipMotionPort {
        constructor(host) {
          this._eval = void 0;
          this._eval = host;
        }
        evaluate(progress, context) {
          return this._eval[evaluatePortTag](progress, context);
        }
        reenter() {
          this._eval.reenter();
        }
      }

      var _dec$1h, _class$1g, _class2$17, _initializer$12, _dec2$11, _class4$d, _class5$c, _initializer2$T;
      const {
        ccclass: ccclass$A,
        serializable: serializable$f
      } = _decorator;
      let AnimationBlendItem = (_dec$1h = ccclass$A(`${CLASS_NAME_PREFIX_ANIM}AnimationBlendItem`), _dec$1h(_class$1g = (_class2$17 = class AnimationBlendItem {
        constructor() {
          this.motion = _initializer$12 && _initializer$12();
        }
        clone() {
          const that = new AnimationBlendItem();
          this._copyTo(that);
          return that;
        }
        _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;
        }
      }, (_initializer$12 = applyDecoratedInitializer(_class2$17.prototype, "motion", [serializable$f], function () {
        return null;
      })), _class2$17)) || _class$1g);
      let AnimationBlend = (_dec2$11 = ccclass$A(`${CLASS_NAME_PREFIX_ANIM}AnimationBlend`), _dec2$11(_class4$d = (_class5$c = class AnimationBlend extends Motion {
        constructor(...args) {
          super(...args);
          this.name = _initializer2$T && _initializer2$T();
        }
        copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        }
      }, (_initializer2$T = applyDecoratedInitializer(_class5$c.prototype, "name", [serializable$f], function () {
        return '';
      })), _class5$c)) || _class4$d);
      class AnimationBlendEval {
        constructor(context, ignoreEmbeddedPlayers, base, children, inputs) {
          this._childEvaluators = children.map(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 = [...inputs];
        }
        createPort() {
          return new AnimationBlendPort(this, this._childEvaluators.map(childEval => {
            var _childEval$createPort;
            return (_childEval$createPort = childEval === null || childEval === void 0 ? void 0 : childEval.createPort()) !== null && _childEval$createPort !== void 0 ? _childEval$createPort : null;
          }));
        }
        get childCount() {
          return this._weights.length;
        }
        getChildWeight(childIndex) {
          return this._weights[childIndex];
        }
        getChildMotionEval(childIndex) {
          return this._childEvaluators[childIndex];
        }
        get duration() {
          let uniformDuration = 0.0;
          for (let iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
            var _this$_childEvaluator, _this$_childEvaluator2;
            uniformDuration += ((_this$_childEvaluator = (_this$_childEvaluator2 = this._childEvaluators[iChild]) === null || _this$_childEvaluator2 === void 0 ? void 0 : _this$_childEvaluator2.duration) !== null && _this$_childEvaluator !== void 0 ? _this$_childEvaluator : 0.0) * this._weights[iChild];
          }
          return uniformDuration;
        }
        getClipStatuses(baseWeight) {
          const {
            _childEvaluators: children,
            _weights: weights
          } = this;
          const nChildren = children.length;
          let iChild = 0;
          let currentChildIterator;
          return {
            next() {
              while (true) {
                if (currentChildIterator) {
                  const result = currentChildIterator.next();
                  if (!result.done) {
                    return result;
                  }
                }
                if (iChild >= nChildren) {
                  return {
                    done: true,
                    value: undefined
                  };
                } else {
                  const child = children[iChild];
                  currentChildIterator = child === null || child === void 0 ? void 0 : child.getClipStatuses(baseWeight * weights[iChild]);
                  ++iChild;
                }
              }
            }
          };
        }
        __evaluatePort(port, progress, context) {
          const nChild = this._childEvaluators.length;
          let sumWeight = 0.0;
          let finalPose = null;
          for (let iChild = 0; iChild < nChild; ++iChild) {
            var _port$childPorts$iChi;
            const childWeight = this._weights[iChild];
            if (!childWeight) {
              continue;
            }
            const 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) {
                const t = childWeight / sumWeight;
                blendPoseInto(finalPose, childOutput, t);
              }
              context.popPose();
            }
          }
          if (finalPose) {
            return finalPose;
          }
          return context.pushDefaultedPose();
        }
        overrideClips(context) {
          for (let iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
            var _this$_childEvaluator3;
            (_this$_childEvaluator3 = this._childEvaluators[iChild]) === null || _this$_childEvaluator3 === void 0 ? void 0 : _this$_childEvaluator3.overrideClips(context);
          }
        }
        setInput(value, index) {
          this._inputs[index] = value;
          this.doEval();
        }
        doEval() {
          this.eval(this._weights, this._inputs);
        }
      }
      class AnimationBlendPort {
        constructor(host, childPorts) {
          this.childPorts = [];
          this._host = void 0;
          this._host = host;
          this.childPorts = childPorts;
        }
        evaluate(progress, context) {
          return this._host.__evaluatePort(this, progress, context);
        }
        reenter() {
          const {
            childPorts
          } = this;
          const nChildPorts = childPorts.length;
          for (let iChild = 0; iChild < nChildPorts; ++iChild) {
            var _childPorts$iChild;
            (_childPorts$iChild = childPorts[iChild]) === null || _childPorts$iChild === void 0 ? void 0 : _childPorts$iChild.reenter();
          }
        }
      }

      var _dec$1g, _class$1f, _class2$16, _initializer$11, _initializer2$S, _dec2$10, _class4$c, _class5$b, _initializer3$G, _initializer4$A;
      const {
        ccclass: ccclass$z,
        serializable: serializable$e
      } = _decorator;
      let BindableNumber = (_dec$1g = ccclass$z(`${CLASS_NAME_PREFIX_ANIM}BindableNumber`), _dec$1g(_class$1f = (_class2$16 = class BindableNumber {
        constructor(value = 0.0) {
          this.variable = _initializer$11 && _initializer$11();
          this.value = _initializer2$S && _initializer2$S();
          this.value = value;
        }
        clone() {
          const that = new BindableNumber();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        }
      }, (_initializer$11 = applyDecoratedInitializer(_class2$16.prototype, "variable", [serializable$e], function () {
        return '';
      }), _initializer2$S = applyDecoratedInitializer(_class2$16.prototype, "value", [serializable$e], function () {
        return 0.0;
      })), _class2$16)) || _class$1f);
      let BindableBoolean = (_dec2$10 = ccclass$z(`${CLASS_NAME_PREFIX_ANIM}BindableBoolean`), _dec2$10(_class4$c = (_class5$b = class BindableBoolean {
        constructor(value = false) {
          this.variable = _initializer3$G && _initializer3$G();
          this.value = _initializer4$A && _initializer4$A();
          this.value = value;
        }
        clone() {
          const that = new BindableBoolean();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        }
      }, (_initializer3$G = applyDecoratedInitializer(_class5$b.prototype, "variable", [serializable$e], function () {
        return '';
      }), _initializer4$A = applyDecoratedInitializer(_class5$b.prototype, "value", [serializable$e], function () {
        return false;
      })), _class5$b)) || _class4$c);
      function bindOr(context, bindable, type, callback, thisArg, ...args) {
        const {
          variable,
          value
        } = bindable;
        if (!variable) {
          return value;
        }
        const varInstance = context.getVar(variable);
        if (!validateVariableExistence(varInstance, variable)) {
          return value;
        }
        if (varInstance.type !== type) {
          throw new VariableTypeMismatchedError(variable, 'number');
        }
        const initialValue = varInstance.bind(callback, thisArg, ...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 !== 2) {
          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 {
          let iUpper = 0;
          for (let iThresholds = 1; iThresholds < thresholds.length; ++iThresholds) {
            if (thresholds[iThresholds] > value) {
              iUpper = iThresholds;
              break;
            }
          }
          const lower = thresholds[iUpper - 1];
          const upper = thresholds[iUpper];
          const dVal = upper - lower;
          weights[iUpper - 1] = (upper - value) / dVal;
          weights[iUpper] = (value - lower) / dVal;
        }
      }

      var _dec$1f, _class$1e, _class2$15, _initializer$10, _dec2$$, _class4$b, _class5$a, _initializer2$R, _initializer3$F, _class6$6;
      const {
        ccclass: ccclass$y,
        serializable: serializable$d
      } = _decorator;
      let AnimationBlend1DItem = (_dec$1f = ccclass$y(`${CLASS_NAME_PREFIX_ANIM}AnimationBlend1DItem`), _dec$1f(_class$1e = (_class2$15 = class AnimationBlend1DItem extends AnimationBlendItem {
        constructor(...args) {
          super(...args);
          this.threshold = _initializer$10 && _initializer$10();
        }
        clone() {
          const that = new AnimationBlend1DItem();
          this._copyTo(that);
          return that;
        }
        _copyTo(that) {
          super._copyTo(that);
          that.threshold = this.threshold;
          return that;
        }
      }, (_initializer$10 = applyDecoratedInitializer(_class2$15.prototype, "threshold", [serializable$d], function () {
        return 0.0;
      })), _class2$15)) || _class$1e);
      let AnimationBlend1D = (_dec2$$ = ccclass$y('cc.animation.AnimationBlend1D'), _dec2$$(_class4$b = (_class5$a = (_class6$6 = class AnimationBlend1D extends AnimationBlend {
        constructor(...args) {
          super(...args);
          this._items = _initializer2$R && _initializer2$R();
          this.param = _initializer3$F && _initializer3$F();
        }
        get items() {
          return this._items;
        }
        set items(value) {
          this._items = Array.from(value).sort(({
            threshold: lhs
          }, {
            threshold: rhs
          }) => lhs - rhs);
        }
        clone() {
          const that = new AnimationBlend1D();
          this.copyTo(that);
          that._items = this._items.map(item => item.clone());
          that.param = this.param.clone();
          return that;
        }
        [createEval](context, ignoreEmbeddedPlayers) {
          const evaluation = new AnimationBlend1DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(({
            threshold
          }) => threshold), 0.0);
          const initialValue = bindOr(context, this.param, 0, evaluation.setInput, evaluation, 0);
          evaluation.setInput(initialValue, 0);
          return evaluation;
        }
      }, _class6$6.Item = AnimationBlend1DItem, _class6$6), (_initializer2$R = applyDecoratedInitializer(_class5$a.prototype, "_items", [serializable$d], function () {
        return [];
      }), _initializer3$F = applyDecoratedInitializer(_class5$a.prototype, "param", [serializable$d], function () {
        return new BindableNumber();
      })), _class5$a)) || _class4$b);
      class AnimationBlend1DEval extends AnimationBlendEval {
        constructor(context, ignoreEmbeddedPlayers, base, items, thresholds, input) {
          super(context, ignoreEmbeddedPlayers, base, items, [input]);
          this._thresholds = thresholds;
          this.doEval();
        }
        eval(weights, [value]) {
          blend1D(weights, this._thresholds, value);
        }
      }

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

      var _dec$1e, _class$1d, _class2$14, _initializer$$, _dec2$_, _class4$a, _class5$9, _initializer2$Q, _initializer3$E, _initializer4$z, _initializer5$r, _class6$5;
      const {
        ccclass: ccclass$x,
        serializable: serializable$c
      } = _decorator;
      const Algorithm = {
        "SIMPLE_DIRECTIONAL": 0,
        "FREEFORM_CARTESIAN": 1,
        "FREEFORM_DIRECTIONAL": 2
      };
      ccenum(Algorithm);
      let AnimationBlend2DItem = (_dec$1e = ccclass$x(`${CLASS_NAME_PREFIX_ANIM}AnimationBlend2DItem`), _dec$1e(_class$1d = (_class2$14 = class AnimationBlend2DItem extends AnimationBlendItem {
        constructor(...args) {
          super(...args);
          this.threshold = _initializer$$ && _initializer$$();
        }
        clone() {
          const that = new AnimationBlend2DItem();
          this._copyTo(that);
          return that;
        }
        _copyTo(that) {
          super._copyTo(that);
          Vec2.copy(that.threshold, this.threshold);
          return that;
        }
      }, (_initializer$$ = applyDecoratedInitializer(_class2$14.prototype, "threshold", [serializable$c], function () {
        return new Vec2();
      })), _class2$14)) || _class$1d);
      let AnimationBlend2D = (_dec2$_ = ccclass$x('cc.animation.AnimationBlend2D'), _dec2$_(_class4$a = (_class5$9 = (_class6$5 = class AnimationBlend2D extends AnimationBlend {
        constructor(...args) {
          super(...args);
          this._items = _initializer2$Q && _initializer2$Q();
          this.paramX = _initializer3$E && _initializer3$E();
          this.paramY = _initializer4$z && _initializer4$z();
          this._algorithm = _initializer5$r && _initializer5$r();
          this._polarSpaceGBI = undefined;
        }
        get algorithm() {
          return this._algorithm;
        }
        set algorithm(value) {
          if (value === this._algorithm) {
            return;
          }
          this._algorithm = value;
          this._tryReconstructPolarSpaceInterpolator();
        }
        get items() {
          return this._items;
        }
        set items(items) {
          this._items = Array.from(items);
          this._tryReconstructPolarSpaceInterpolator();
        }
        __callOnAfterDeserializeRecursive() {
          this._tryReconstructPolarSpaceInterpolator();
        }
        clone() {
          const that = new AnimationBlend2D();
          this.copyTo(that);
          that._items = this._items.map(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;
        }
        [createEval](context, ignoreEmbeddedPlayers) {
          const {
            algorithm
          } = this;
          let evaluation;
          switch (algorithm) {
            case 2:
              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 0:
            case 1:
              evaluation = new AnimationBlend2DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(({
                threshold
              }) => threshold), algorithm, [0.0, 0.0]);
              break;
          }
          const initialValueX = bindOr(context, this.paramX, 0, evaluation.setInput, evaluation, 0);
          const initialValueY = bindOr(context, this.paramY, 0, evaluation.setInput, evaluation, 1);
          evaluation.setInput(initialValueX, 0);
          evaluation.setInput(initialValueY, 1);
          return evaluation;
        }
        _tryReconstructPolarSpaceInterpolator() {
          if (this._algorithm === 2) {
            this._polarSpaceGBI = new PolarSpaceGradientBandInterpolator2D(this._items.map(item => item.threshold));
          } else {
            this._polarSpaceGBI = undefined;
          }
        }
      }, _class6$5.Algorithm = Algorithm, _class6$5.Item = AnimationBlend2DItem, _class6$5), (_initializer2$Q = applyDecoratedInitializer(_class5$9.prototype, "_items", [serializable$c], function () {
        return [];
      }), _initializer3$E = applyDecoratedInitializer(_class5$9.prototype, "paramX", [serializable$c], function () {
        return new BindableNumber();
      }), _initializer4$z = applyDecoratedInitializer(_class5$9.prototype, "paramY", [serializable$c], function () {
        return new BindableNumber();
      }), _initializer5$r = applyDecoratedInitializer(_class5$9.prototype, "_algorithm", [serializable$c], function () {
        return 0;
      })), _class5$9)) || _class4$a);
      class AnimationBlend2DEval extends AnimationBlendEval {
        constructor(context, ignoreEmbeddedPlayers, base, items, thresholds, algorithm, inputs) {
          super(context, ignoreEmbeddedPlayers, base, items, inputs);
          this._thresholds = void 0;
          this._algorithm = void 0;
          this._value = new Vec2();
          this._thresholds = thresholds;
          this._algorithm = algorithm;
          this.doEval();
        }
        eval(weights, [x, y]) {
          Vec2.set(this._value, x, y);
          weights.fill(0);
          switch (this._algorithm) {
            case 0:
              blendSimpleDirectional(weights, this._thresholds, this._value);
              break;
            case 1:
              sampleFreeformCartesian(weights, this._thresholds, this._value);
              break;
          }
        }
      }
      class PolarSpaceGradientBandBlend2DEval extends AnimationBlendEval {
        constructor(context, ignoreEmbeddedPlayers, base, items, interpolator, inputs) {
          super(context, ignoreEmbeddedPlayers, base, items, inputs);
          this._interpolator = void 0;
          this._value = new Vec2();
          this._interpolator = interpolator;
          this.doEval();
        }
        eval(weights, [x, y]) {
          Vec2.set(this._value, x, y);
          weights.fill(0);
          this._interpolator.interpolate(weights, this._value);
        }
      }

      var _dec$1d, _class$1c, _class2$13, _initializer$_, _dec2$Z, _class4$9, _class5$8, _initializer2$P, _class6$4;
      const {
        ccclass: ccclass$w,
        serializable: serializable$b
      } = _decorator;
      let AnimationBlendDirectItem = (_dec$1d = ccclass$w(`${CLASS_NAME_PREFIX_ANIM}AnimationBlendDirectItem`), _dec$1d(_class$1c = (_class2$13 = class AnimationBlendDirectItem extends AnimationBlendItem {
        constructor(...args) {
          super(...args);
          this.weight = _initializer$_ && _initializer$_();
        }
        clone() {
          const that = new AnimationBlendDirectItem();
          this._copyTo(that);
          return that;
        }
        _copyTo(that) {
          super._copyTo(that);
          that.weight = this.weight;
          return that;
        }
      }, (_initializer$_ = applyDecoratedInitializer(_class2$13.prototype, "weight", [serializable$b], function () {
        return new BindableNumber(0.0);
      })), _class2$13)) || _class$1c);
      (_dec2$Z = ccclass$w('cc.animation.AnimationBlendDirect'), _dec2$Z(_class4$9 = (_class5$8 = (_class6$4 = class AnimationBlendDirect extends AnimationBlend {
        constructor(...args) {
          super(...args);
          this._items = _initializer2$P && _initializer2$P();
        }
        get items() {
          return this._items;
        }
        set items(value) {
          this._items = Array.from(value);
        }
        clone() {
          const that = new AnimationBlendDirect();
          this.copyTo(that);
          that._items = this._items.map(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;
        }
        [createEval](context, ignoreEmbeddedPlayers) {
          const myEval = new AnimationBlendDirectEval(context, ignoreEmbeddedPlayers, this, this._items, new Array(this._items.length).fill(0.0));
          for (let iItem = 0; iItem < this._items.length; ++iItem) {
            const item = this._items[iItem];
            const initialValue = bindOr(context, item.weight, 0, myEval.setInput, myEval, iItem);
            myEval.setInput(initialValue, iItem);
          }
          return myEval;
        }
      }, _class6$4.Item = AnimationBlendDirectItem, _class6$4), (_initializer2$P = applyDecoratedInitializer(_class5$8.prototype, "_items", [serializable$b], function () {
        return [];
      })), _class5$8)) || _class4$9);
      class AnimationBlendDirectEval extends AnimationBlendEval {
        constructor(...args) {
          super(...args);
          this.doEval();
        }
        eval(weights, inputs) {
          const nChildren = weights.length;
          for (let iChild = 0; iChild < nChildren; ++iChild) {
            weights[iChild] = inputs[iChild];
          }
        }
      }

      var _dec$1c, _class$1b, _class2$12, _initializer$Z, _initializer2$O, _dec2$Y, _dec3$O, _class4$8, _class5$7, _initializer3$D;
      let JointMask = (_dec$1c = ccclass$H('cc.JointMask'), _dec$1c(_class$1b = (_class2$12 = class JointMask {
        constructor() {
          this.path = _initializer$Z && _initializer$Z();
          this.enabled = _initializer2$O && _initializer2$O();
        }
      }, (_initializer$Z = applyDecoratedInitializer(_class2$12.prototype, "path", [serializable$l], function () {
        return '';
      }), _initializer2$O = applyDecoratedInitializer(_class2$12.prototype, "enabled", [serializable$l], function () {
        return true;
      })), _class2$12)) || _class$1b);
      (_dec2$Y = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AnimationMask`), _dec3$O = type$a(JointMask), _dec2$Y(_class4$8 = (_class5$7 = class AnimationMask extends Asset {
        constructor(...args) {
          super(...args);
          this._jointMasks = _initializer3$D && _initializer3$D();
        }
        get joints() {
          return this._jointMasks;
        }
        set joints(value) {
          this.clear();
          for (const joint of value) {
            this.addJoint(joint.path, joint.enabled);
          }
        }
        addJoint(path, enabled) {
          this.removeJoint(path);
          const info = new JointMask();
          info.path = path;
          info.enabled = enabled;
          this._jointMasks.push(info);
        }
        removeJoint(removal) {
          removeIf(this._jointMasks, ({
            path
          }) => path === removal);
        }
        clear() {
          this._jointMasks.length = 0;
        }
        filterDisabledNodes(root) {
          const {
            _jointMasks: jointMasks
          } = this;
          const nJointMasks = jointMasks.length;
          const disabledNodes = new Set();
          for (let iJointMask = 0; iJointMask < nJointMasks; ++iJointMask) {
            const {
              path,
              enabled
            } = jointMasks[iJointMask];
            if (enabled) {
              continue;
            }
            const node = root.getChildByPath(path);
            if (node) {
              disabledNodes.add(node);
            }
          }
          return disabledNodes;
        }
        isExcluded(path) {
          var _this$_jointMasks$fin, _this$_jointMasks$fin2;
          return !((_this$_jointMasks$fin = (_this$_jointMasks$fin2 = this._jointMasks.find(({
            path: p
          }) => p === path)) === null || _this$_jointMasks$fin2 === void 0 ? void 0 : _this$_jointMasks$fin2.enabled) !== null && _this$_jointMasks$fin !== void 0 ? _this$_jointMasks$fin : true);
        }
      }, (_initializer3$D = applyDecoratedInitializer(_class5$7.prototype, "_jointMasks", [serializable$l], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$7.prototype, "joints", [_dec3$O], Object.getOwnPropertyDescriptor(_class5$7.prototype, "joints"), _class5$7.prototype)), _class5$7)) || _class4$8);

      let _Symbol$iterator;
      var _dec$1b, _class$1a, _class2$11, _initializer$Y, _initializer2$N, _dec2$X, _dec3$N, _class4$7, _class5$6, _initializer3$C, _initializer4$y, _dec4$z, _class7, _class8, _initializer5$q;
      let ClipOverrideEntry = (_dec$1b = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ClipOverrideEntry`), _dec$1b(_class$1a = (_class2$11 = class ClipOverrideEntry {
        constructor() {
          this.original = _initializer$Y && _initializer$Y();
          this.substitution = _initializer2$N && _initializer2$N();
        }
      }, (_initializer$Y = applyDecoratedInitializer(_class2$11.prototype, "original", [serializable$l], function () {
        return null;
      }), _initializer2$N = applyDecoratedInitializer(_class2$11.prototype, "substitution", [serializable$l], function () {
        return null;
      })), _class2$11)) || _class$1a);
      let AnimationGraphVariant = (_dec2$X = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}AnimationGraphVariant`), _dec3$N = type$a(AnimationGraph), _dec2$X(_class4$7 = (_class5$6 = class AnimationGraphVariant extends AnimationGraphLike {
        constructor(...args) {
          super(...args);
          this._graph = _initializer3$C && _initializer3$C();
          this._clipOverrides = _initializer4$y && _initializer4$y();
        }
        get original() {
          return this._graph;
        }
        set original(value) {
          this._graph = value;
        }
        get clipOverrides() {
          return this._clipOverrides;
        }
      }, (_applyDecoratedDescriptor(_class5$6.prototype, "original", [_dec3$N], Object.getOwnPropertyDescriptor(_class5$6.prototype, "original"), _class5$6.prototype), _initializer3$C = applyDecoratedInitializer(_class5$6.prototype, "_graph", [serializable$l], function () {
        return null;
      }), _initializer4$y = applyDecoratedInitializer(_class5$6.prototype, "_clipOverrides", [serializable$l], function () {
        return new ClipOverrideMap();
      })), _class5$6)) || _class4$7);
      let ClipOverrideMap = (_dec4$z = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}ClipOverrideMap`), _dec4$z(_class7 = (_class8 = (_Symbol$iterator = Symbol.iterator, class ClipOverrideMap {
        constructor() {
          this._entries = _initializer5$q && _initializer5$q();
        }
        get size() {
          return this._entries.length;
        }
        [_Symbol$iterator]() {
          return this._entries[Symbol.iterator]();
        }
        has(original) {
          return !!this._entries.find(({
            original: o
          }) => o === original);
        }
        get(original) {
          const entry = this._entries.find(({
            original: o
          }) => o === original);
          return entry === null || entry === void 0 ? void 0 : entry.substitution;
        }
        set(original, substitution) {
          const entry = this._entries.find(({
            original: o
          }) => o === original);
          if (entry) {
            entry.substitution = substitution;
          } else {
            const newEntry = new ClipOverrideEntry();
            newEntry.original = original;
            newEntry.substitution = substitution;
            this._entries.push(newEntry);
          }
        }
        delete(original) {
          removeIf(this._entries, ({
            original: o
          }) => o === original);
        }
        clear() {
          this._entries.length = 0;
        }
      }), (_initializer5$q = applyDecoratedInitializer(_class8.prototype, "_entries", [serializable$l], function () {
        return [];
      })), _class8)) || _class7);

      const MAX_ANIMATION_LAYER = 32;

      const TRANSFORM_STRIDE_IN_FLOATS = 10;
      const TRANSFORM_STRIDE_IN_BYTES = 8 * TRANSFORM_STRIDE_IN_FLOATS;
      const ROTATION_OFFSET = 3;
      const SCALE_OFFSET = ROTATION_OFFSET + 4;
      class TransformArray {
        static get BYTES_PER_ELEMENT() {
          return TRANSFORM_STRIDE_IN_BYTES;
        }
        constructor(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);
          }
        }
        get buffer() {
          return this._data.buffer;
        }
        get byteLength() {
          return this._data.byteLength;
        }
        get byteOffset() {
          return this._data.byteOffset;
        }
        get length() {
          return this._data.length / TRANSFORM_STRIDE_IN_FLOATS;
        }
        getTransform(index, out) {
          const {
            _data: data
          } = this;
          const {
            position,
            rotation,
            scale
          } = out;
          const 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;
        }
        getPosition(index, out) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset);
          return out;
        }
        getRotation(index, out) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.fromArray(out, data, baseOffset + ROTATION_OFFSET);
          return out;
        }
        getScale(index, out) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset + SCALE_OFFSET);
          return out;
        }
        setTransform(index, value) {
          const {
            _data: data
          } = this;
          const {
            position,
            rotation,
            scale
          } = value;
          const 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);
        }
        setPosition(index, value) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset);
        }
        setRotation(index, value) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.toArray(data, value, baseOffset + ROTATION_OFFSET);
        }
        setScale(index, value) {
          const {
            _data: data
          } = this;
          const baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset + SCALE_OFFSET);
        }
        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);
        }
        fill(value, start, end) {
          var _start, _end;
          const {
            length
          } = this;
          (_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 (let i = start + 1; i < end; ++i) {
            this.copyWithin(i, start, start + 1);
          }
        }
        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);
        }
        set(transformArray, targetOffset) {
          this._data.set(transformArray._data, typeof targetOffset === 'number' ? targetOffset * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        }
        slice(start, end) {
          const 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);
        }
        copyRange(targetOffset, source, sourceOffset, size) {
          const sizeInFloats = TRANSFORM_STRIDE_IN_FLOATS * size;
          const targetFloats = this._data;
          const targetStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * targetOffset;
          const sourceFloats = source._data;
          const sourceStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * sourceOffset;
          for (let i = 0; i < sizeInFloats; ++i) {
            targetFloats[targetStartInFloats + i] = sourceFloats[sourceStartInFloats + i];
          }
        }
      }

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

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

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

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

      var _dec$1a, _dec2$W, _dec3$M, _dec4$y, _dec5$w, _dec6$o, _dec7$h, _class3$p;
      function findBoneByNameRecursively(from, name) {
        if (from.name === name) {
          return from;
        }
        const nChildren = from.children.length;
        for (let iChild = 0; iChild < nChildren; ++iChild) {
          const found = findBoneByNameRecursively(from.children[iChild], name);
          if (found) {
            return found;
          }
        }
        return null;
      }
      class AnimationGraphBindingContext {
        constructor(origin, poseLayoutMaintainer, varRegistry, _controller) {
          this._origin = void 0;
          this._layoutMaintainer = void 0;
          this._varRegistry = void 0;
          this._additiveFlagStack = [];
          this._triggerResetter = name => 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];
        }
        get origin() {
          return this._origin;
        }
        get controller() {
          return this._controller;
        }
        get triggerResetter() {
          return this._triggerResetter;
        }
        get clipOverrides() {
          return this._clipOverrides;
        }
        get additive() {
          const {
            _additiveFlagStack: additiveFlagStack
          } = this;
          return additiveFlagStack[additiveFlagStack.length - 1];
        }
        bindTransform(bone) {
          const boneNode = this._origin.getChildByPath(bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        }
        bindTransformByName(bone) {
          const boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        }
        getBoneChildren(bone) {
          const boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return [];
          }
          return boneNode.children.map(childNode => childNode.name);
        }
        getParentBoneNameByName(bone) {
          var _boneNode$parent;
          const 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;
        }
        bindAuxiliaryCurve(name) {
          return this._layoutMaintainer.getOrCreateAuxiliaryCurveBinding(name);
        }
        getEvaluationTimeAuxiliaryCurveView() {
          return this._layoutMaintainer.auxiliaryCurveRegistry;
        }
        getVar(id) {
          return this._varRegistry[id];
        }
        _pushAdditiveFlag(additive) {
          this._additiveFlagStack.push(additive);
        }
        _popAdditiveFlag() {
          assertIsTrue(this._additiveFlagStack.length > 1);
          this._additiveFlagStack.pop();
        }
        _integrityCheck() {
          return this._additiveFlagStack.length === 1;
        }
        get stashView() {
          assertIsTrue(this._stashView);
          return this._stashView;
        }
        get motionSyncManager() {
          assertIsTrue(this._motionSyncManager);
          return this._motionSyncManager;
        }
        _setLayerWideContextProperties(stashView, motionSyncManager) {
          assertIsTrue(!this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = true;
          this._stashView = stashView;
          this._motionSyncManager = motionSyncManager;
        }
        _unsetLayerWideContextProperties() {
          assertIsTrue(this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = false;
          this._stashView = undefined;
          this._motionSyncManager = undefined;
        }
        _setClipOverrides(clipOverrides) {
          this._clipOverrides = clipOverrides;
        }
        _resetTrigger(triggerName) {
          const varInstance = this._varRegistry[triggerName];
          if (!varInstance) {
            return;
          }
          varInstance.value = false;
        }
      }
      const cacheTransform = new Transform$1();
      class AuxiliaryCurveRegistry {
        constructor() {
          this._namedCurves = new Map();
        }
        names() {
          return this._namedCurves.keys();
        }
        has(name) {
          return this._namedCurves.has(name);
        }
        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;
        }
        set(name, value) {
          this._namedCurves.set(name, value);
        }
      }
      const checkBindStatus = (bindStarted = false) => (_, _propertyKey, descriptor) => {
        const vendor = descriptor.value;
        if (vendor) {
          descriptor.value = function (...args) {
            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.`);
            return vendor.call(this, ...args);
          };
        }
      };
      let AnimationGraphPoseLayoutMaintainer = (_dec$1a = checkBindStatus(true), _dec2$W = checkBindStatus(true), _dec3$M = checkBindStatus(true), _dec4$y = checkBindStatus(true), _dec5$w = checkBindStatus(true), _dec6$o = checkBindStatus(false), _dec7$h = checkBindStatus(true), (_class3$p = class AnimationGraphPoseLayoutMaintainer {
        constructor(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;
        }
        get transformCount() {
          return this._transformRecords.length;
        }
        get auxiliaryCurveCount() {
          return this._auxiliaryCurveRecords.length;
        }
        get auxiliaryCurveRegistry() {
          return this._auxiliaryCurveRegistry;
        }
        getOrCreateTransformBinding(node) {
          const {
            _origin: origin
          } = this;
          let debugIntegrityCheckLengthOfPathToOrigin = 0;
          let isValidNode = false;
          for (let current = node; current; current = current.parent) {
            if (current === origin) {
              isValidNode = true;
              break;
            }
            {
              ++debugIntegrityCheckLengthOfPathToOrigin;
            }
          }
          if (!isValidNode) {
            return null;
          }
          const handle = this._getOrCreateTransformBinding(node);
          if (node !== origin) {
            {
              --debugIntegrityCheckLengthOfPathToOrigin;
              assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
            }
            for (let parent = node.parent; parent !== origin; parent = parent.parent) {
              assertIsTrue(parent);
              void this._getOrCreateTransformBinding(parent);
              {
                --debugIntegrityCheckLengthOfPathToOrigin;
                assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
              }
            }
          }
          {
            assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin === 0);
          }
          return handle;
        }
        _getOrCreateTransformBinding(node) {
          const {
            _transformRecords: transformRecords
          } = this;
          const transformIndex = transformRecords.findIndex(transformRecord => transformRecord.node === node);
          if (transformIndex >= 0) {
            const transformRecord = transformRecords[transformIndex];
            ++transformRecord.refCount;
            return transformRecord.handle;
          }
          let newNodeIndex = 0;
          for (let parent = node.parent; parent; parent = parent.parent) {
            const parentIndex = transformRecords.findIndex(transformRecord => transformRecord.node === parent);
            if (parentIndex >= 0) {
              newNodeIndex = parentIndex + 1;
              break;
            }
          }
          for (let transformIndex = newNodeIndex; transformIndex < transformRecords.length; ++transformIndex) {
            ++transformRecords[transformIndex].handle.index;
          }
          const transformRecord = new TransformRecord(new TransformHandleInternal(this, newNodeIndex), node);
          transformRecords.splice(newNodeIndex, 0, transformRecord);
          return transformRecord.handle;
        }
        getOrCreateAuxiliaryCurveBinding(name) {
          const {
            _auxiliaryCurveRecords: auxiliaryCurveRecords
          } = this;
          const auxiliaryCurveIndex = auxiliaryCurveRecords.findIndex(record => record.name === name);
          if (auxiliaryCurveIndex >= 0) {
            const auxiliaryCurveRecord = auxiliaryCurveRecords[auxiliaryCurveIndex];
            ++auxiliaryCurveRecord.refCount;
            return auxiliaryCurveRecord.handle;
          } else {
            const newAuxiliaryCurveIndex = auxiliaryCurveRecords.length;
            const auxiliaryCurveRecord = new AuxiliaryCurveRecord(new AuxiliaryCurveHandleInternal(this, newAuxiliaryCurveIndex), name);
            auxiliaryCurveRecords.push(auxiliaryCurveRecord);
            return auxiliaryCurveRecord.handle;
          }
        }
        createEvaluationContext() {
          assertIsTrue(!this._bindStarted);
          return new AnimationGraphEvaluationContext(this.transformCount, this.auxiliaryCurveCount, this._parentTable.slice(), this._origin);
        }
        resetPoseStashAllocator(allocator) {
          assertIsTrue(!this._bindStarted);
          allocator._reset(this.transformCount, this.auxiliaryCurveCount);
        }
        createTransformFilter(mask) {
          const {
            _origin: origin
          } = this;
          const involvedTransformIndices = [];
          for (const {
            node,
            handle
          } of this._transformRecords) {
            const 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();
          const poseFilter = new TransformFilter(involvedTransformIndices);
          return poseFilter;
          function countPath(from, to) {
            const path = [];
            for (let node = to; node; node = node.parent) {
              if (node === from) {
                return path.join('/');
              } else {
                path.unshift(node.name);
              }
            }
            return undefined;
          }
        }
        fetchDefaultTransforms(transforms) {
          const nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
            const {
              defaultTransform
            } = this._transformRecords[iTransform];
            transforms.setTransform(iTransform, defaultTransform);
          }
        }
        apply(pose) {
          const {
            transforms,
            auxiliaryCurves
          } = pose;
          const nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
            const transform = transforms.getTransform(iTransform, cacheTransform);
            const {
              node
            } = this._transformRecords[iTransform];
            node.setRTS(transform.rotation, transform.position, transform.scale);
          }
          const nAuxiliaryCurves = this._auxiliaryCurveRecords.length;
          for (let iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            const {
              name: curveName
            } = this._auxiliaryCurveRecords[iAuxiliaryCurve];
            const curveValue = auxiliaryCurves[iAuxiliaryCurve];
            this._auxiliaryCurveRegistry.set(curveName, curveValue);
          }
        }
        _destroyTransformHandle(index) {
          assertIsTrue(index >= 0 && index < this._transformRecords.length, `Invalid transform handle.`);
          const record = this._transformRecords[index];
          assertIsTrue(record.refCount > 0, `Something work wrong: refCount mismatch.`);
          --record.refCount;
        }
        _destroyAuxiliaryCurveHandle(index) {
          assertIsTrue(index >= 0 && index < this._auxiliaryCurveRecords.length, `Invalid auxiliary value handle.`);
          const record = this._auxiliaryCurveRecords[index];
          assertIsTrue(record.refCount > 0, `Something work wrong: refCount mismatch.`);
          --record.refCount;
        }
        startBind() {
          this._bindStarted = true;
          this._transformCountBeforeBind = this._transformRecords.length;
          this._auxiliaryCurveCountBeforeBind = this._auxiliaryCurveRecords.length;
        }
        endBind() {
          const {
            _transformRecords: transformRecords,
            _auxiliaryCurveRecords: auxiliaryCurveRecords
          } = this;
          let changeFlags = 0;
          trimRecords(transformRecords);
          if (transformRecords.length !== this._transformCountBeforeBind) {
            changeFlags |= 1;
            const nRecords = transformRecords.length;
            for (let iRecord = 0; iRecord < nRecords; ++iRecord) {
              const record = transformRecords[iRecord];
              record.order = iRecord;
            }
          } else {
            const nRecords = transformRecords.length;
            let orderChanged = false;
            for (let iRecord = 0; iRecord < nRecords; ++iRecord) {
              const record = transformRecords[iRecord];
              if (record.order !== iRecord) {
                orderChanged = true;
                record.order = iRecord;
              }
            }
            if (orderChanged) {
              changeFlags |= 2;
            }
          }
          trimRecords(auxiliaryCurveRecords);
          if (auxiliaryCurveRecords.length !== this._auxiliaryCurveCountBeforeBind) {
            changeFlags |= 4;
          }
          const {
            _parentTable: parentTable,
            _origin: origin
          } = this;
          parentTable.length = transformRecords.length;
          for (let iTransform = 0; iTransform < transformRecords.length; ++iTransform) {
            const {
              node
            } = transformRecords[iTransform];
            if (node === origin) {
              parentTable[iTransform] = -1;
              continue;
            }
            const parent = node.parent;
            if (parent === origin) {
              const parentIndex = transformRecords.findIndex(record => record.node === parent);
              parentTable[iTransform] = parentIndex >= 0 ? parentIndex : -1;
            } else {
              const parentIndex = transformRecords.findIndex(record => record.node === parent);
              assertIsTrue(parentIndex >= 0, `Parent node is not bound!`);
              assertIsTrue(parentIndex < iTransform);
              parentTable[iTransform] = parentIndex;
            }
          }
          this._bindStarted = false;
          {
            transformRecords.forEach((transformRecord, index, transformRecords) => {
              assertIsTrue(transformRecord.handle.index === index, `Bad transform handle.`);
              assertIsTrue(transformRecord.order === index, `Bad transform order field.`);
              for (let parent = transformRecord.node.parent; parent; parent = parent.parent) {
                const parentIndex = transformRecords.findIndex(r => r.node === parent);
                if (parentIndex >= 0) {
                  assertIsTrue(parentIndex < index, `Bad transform order.`);
                }
              }
            });
            this._transformCountBeforeBind = -1;
            this._auxiliaryCurveCountBeforeBind = -1;
          }
          return changeFlags;
        }
      }, (_applyDecoratedDescriptor(_class3$p.prototype, "getOrCreateTransformBinding", [_dec$1a], Object.getOwnPropertyDescriptor(_class3$p.prototype, "getOrCreateTransformBinding"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "_getOrCreateTransformBinding", [_dec2$W], Object.getOwnPropertyDescriptor(_class3$p.prototype, "_getOrCreateTransformBinding"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "getOrCreateAuxiliaryCurveBinding", [_dec3$M], Object.getOwnPropertyDescriptor(_class3$p.prototype, "getOrCreateAuxiliaryCurveBinding"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "_destroyTransformHandle", [_dec4$y], Object.getOwnPropertyDescriptor(_class3$p.prototype, "_destroyTransformHandle"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "_destroyAuxiliaryCurveHandle", [_dec5$w], Object.getOwnPropertyDescriptor(_class3$p.prototype, "_destroyAuxiliaryCurveHandle"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "startBind", [_dec6$o], Object.getOwnPropertyDescriptor(_class3$p.prototype, "startBind"), _class3$p.prototype), _applyDecoratedDescriptor(_class3$p.prototype, "endBind", [_dec7$h], Object.getOwnPropertyDescriptor(_class3$p.prototype, "endBind"), _class3$p.prototype)), _class3$p));
      class TransformRecord {
        constructor(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;
          const defaultTransform = new Transform$1();
          defaultTransform.position = node.position;
          defaultTransform.rotation = node.rotation;
          defaultTransform.scale = node.scale;
          this.defaultTransform = defaultTransform;
        }
      }
      class AuxiliaryCurveRecord {
        constructor(handle, name) {
          this.refCount = 1;
          this.handle = void 0;
          this.name = void 0;
          this.handle = handle;
          this.name = name;
        }
      }
      function trimRecords(records) {
        const nUsedRecords = partition(records, record => {
          assertIsTrue(record.refCount >= 0);
          return record.refCount > 0;
        });
        assertIsTrue(nUsedRecords <= records.length);
        if (nUsedRecords === records.length) {
          return;
        }
        for (let iRecord = 0; iRecord < nUsedRecords; ++iRecord) {
          records[iRecord].handle.index = iRecord;
        }
        {
          records.slice(nUsedRecords).forEach(record => record.refCount = -1);
        }
        records.splice(nUsedRecords, records.length - nUsedRecords);
      }
      const defaultTransformsTag = Symbol('[[DefaultTransforms]]');
      class AnimationGraphSettleContext {
        constructor(_layoutMaintainer) {
          this._layoutMaintainer = _layoutMaintainer;
        }
        get transformCount() {
          return this._layoutMaintainer.transformCount;
        }
        createTransformFilter(mask) {
          return this._layoutMaintainer.createTransformFilter(mask);
        }
      }
      const cacheTransform_spaceConversion = new Transform$1();
      const cacheParentTransform_spaceConversion = new Transform$1();
      class AnimationGraphEvaluationContext {
        constructor(transformCount, metaValueCount, parentTable, componentNode) {
          this[defaultTransformsTag] = void 0;
          this._poseAllocator = void 0;
          this._parentTable = void 0;
          this._componentNode = void 0;
          this._cacheComponentToWorldTransform = new Transform$1();
          {
            assertIsTrue(transformCount === parentTable.length);
            assertIsTrue(parentTable.every((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);
        }
        destroy() {
          this._poseAllocator.destroy();
        }
        get allocatedPoseCount() {
          return this._poseAllocator.allocatedCount;
        }
        get parentTable() {
          return this._parentTable;
        }
        pushDefaultedPose() {
          const pose = this._poseAllocator.push();
          pose.transforms.set(this[defaultTransformsTag]);
          pose._poseTransformSpace = 0;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        }
        pushDefaultedPoseInComponentSpace() {
          const pose = this.pushDefaultedPose();
          this._poseTransformsSpaceLocalToComponent(pose);
          return pose;
        }
        pushZeroDeltaPose() {
          const pose = this._poseAllocator.push();
          pose.transforms.fill(ZERO_DELTA_TRANSFORM);
          pose._poseTransformSpace = 0;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        }
        pushDuplicatedPose(src) {
          const pose = this._poseAllocator.push();
          pose.transforms.set(src.transforms);
          pose._poseTransformSpace = src._poseTransformSpace;
          pose.auxiliaryCurves.set(src.auxiliaryCurves);
          return pose;
        }
        popPose() {
          this._poseAllocator.pop();
        }
        get _stackSize_debugging() {
          return this._poseAllocator.allocatedCount;
        }
        _isStackTopPose_debugging(pose) {
          return pose === this._poseAllocator.top;
        }
        _poseTransformsSpaceLocalToComponent(pose) {
          const {
            transforms
          } = pose;
          const {
            length: nTransforms
          } = transforms;
          for (let iTransform = 0; iTransform < nTransforms; ++iTransform) {
            const parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            const transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            const parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
            Transform$1.multiply(transform, parentTransform, transform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = 1;
        }
        _poseTransformsSpaceComponentToLocal(pose) {
          const {
            transforms
          } = pose;
          const {
            length: nTransforms
          } = transforms;
          for (let iTransform = nTransforms - 1; iTransform >= 0; --iTransform) {
            const parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            const transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            const parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
            Transform$1.calculateRelative(transform, transform, parentTransform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = 0;
        }
        _convertPoseSpaceTransformToTargetSpace(transform, outTransformSpace, pose, poseTransformIndex) {
          const poseSpace = pose._poseTransformSpace;
          switch (outTransformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case 0:
              if (poseSpace === 1) {
                Transform$1.multiply(transform, this._getComponentToWorldTransform(), transform);
              } else {
                assertIsTrue(poseSpace === 0);
                Transform$1.multiply(transform, this._getLocalToWorldTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex), transform);
              }
              break;
            case 1:
              if (poseSpace === 1) ; else {
                assertIsTrue(poseSpace === 0);
                Transform$1.multiply(transform, this._getLocalToComponentTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex), transform);
              }
              break;
            case 2:
              {
                if (poseSpace === 1) {
                  const parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    const parentComponentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
                    const invParentComponentTransform = Transform$1.invert(parentComponentTransform, parentComponentTransform);
                    Transform$1.multiply(transform, invParentComponentTransform, transform);
                  }
                } else {
                  assertIsTrue(poseSpace === 0);
                }
                break;
              }
            case 3:
              {
                assertIsTrue(poseSpace === 1 || poseSpace === 0);
                const boneTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion);
                const invBoneTransform = Transform$1.invert(boneTransform, boneTransform);
                Transform$1.multiply(transform, invBoneTransform, transform);
                break;
              }
          }
          return transform;
        }
        _convertTransformToPoseTransformSpace(transform, transformSpace, pose, poseTransformIndex) {
          const poseSpace = pose._poseTransformSpace;
          switch (transformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case 0:
              if (poseSpace === 1) {
                const worldToComponent = Transform$1.invert(cacheParentTransform_spaceConversion, this._getComponentToWorldTransform());
                Transform$1.multiply(transform, worldToComponent, transform);
              } else {
                assertIsTrue(poseSpace === 0);
                const localToWorld = this._getLocalToWorldTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex);
                const worldToLocal = Transform$1.invert(localToWorld, localToWorld);
                Transform$1.multiply(transform, worldToLocal, transform);
              }
              break;
            case 1:
              if (poseSpace === 1) ; else {
                assertIsTrue(poseSpace === 0);
                const localToComponent = this._getLocalToComponentTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex);
                const componentToLocal = Transform$1.invert(localToComponent, localToComponent);
                Transform$1.multiply(transform, componentToLocal, transform);
              }
              break;
            case 2:
              {
                if (poseSpace === 1) {
                  const parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    const parentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
                    Transform$1.multiply(transform, parentTransform, transform);
                  }
                }
                break;
              }
            case 3:
              {
                assertIsTrue(poseSpace === 1 || poseSpace === 0);
                const currentTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion);
                Transform$1.multiply(transform, currentTransform, transform);
                break;
              }
          }
          return transform;
        }
        _getComponentToWorldTransform() {
          const result = this._cacheComponentToWorldTransform;
          const componentNode = this._componentNode;
          result.position = componentNode.worldPosition;
          result.rotation = componentNode.worldRotation;
          result.scale = componentNode.worldScale;
          return result;
        }
        _getLocalToComponentTransform(out, pose, transformIndex) {
          const {
            _parentTable: parentTable
          } = this;
          Transform$1.setIdentity(out);
          for (let iTransform = parentTable[transformIndex]; iTransform >= 0; iTransform = parentTable[iTransform]) {
            const localTransform = pose.transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            Transform$1.multiply(out, localTransform, out);
          }
          return out;
        }
        _getLocalToWorldTransform(out, pose, transformIndex) {
          this._getLocalToComponentTransform(out, pose, transformIndex);
          Transform$1.multiply(out, this._getComponentToWorldTransform(), out);
          return out;
        }
      }
      class TransformHandleInternal {
        constructor(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        destroy() {
          this._host._destroyTransformHandle(this.index);
        }
      }
      class AuxiliaryCurveHandleInternal {
        constructor(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        destroy() {
          this._host._destroyAuxiliaryCurveHandle(this.index);
        }
      }
      class AnimationGraphUpdateContextGenerator {
        constructor() {
          this._context = {
            deltaTime: 0.0,
            indicativeWeight: 0.0
          };
        }
        generate(deltaTime, indicativeWeight) {
          this._context.deltaTime = deltaTime;
          this._context.indicativeWeight = indicativeWeight;
          return this._context;
        }
        forkSubWeight(base, subWeight) {
          this._context.deltaTime = base.deltaTime;
          this._context.indicativeWeight = base.indicativeWeight * subWeight;
        }
      }
      class DeferredPoseStashAllocator {
        constructor() {
          this._allocator = null;
        }
        get allocatedPoseCount() {
          assertIsTrue(this._allocator);
          return this._allocator.allocatedCount;
        }
        _reset(transformCount, auxiliaryCurveCount) {
          this._allocator = new PoseHeapAllocator(transformCount, auxiliaryCurveCount);
        }
        allocatePose() {
          assertIsTrue(this._allocator);
          const pose = this._allocator.allocatePose();
          return pose;
        }
        destroyPose(pose) {
          assertIsTrue(this._allocator);
          return this._allocator.destroyPose(pose);
        }
      }

      var _dec$19, _class$19, _class2$10, _initializer$X, _initializer2$M, _class3$o;
      const {
        ccclass: ccclass$v,
        serializable: serializable$a
      } = _decorator;
      const UnaryOperator = {
        "TRUTHY": 0,
        "FALSY": 1
      };
      (_dec$19 = ccclass$v(`${CLASS_NAME_PREFIX_ANIM}UnaryCondition`), _dec$19(_class$19 = (_class2$10 = (_class3$o = class UnaryCondition {
        constructor() {
          this.operator = _initializer$X && _initializer$X();
          this.operand = _initializer2$M && _initializer2$M();
        }
        clone() {
          const that = new UnaryCondition();
          that.operator = this.operator;
          that.operand = this.operand.clone();
          return that;
        }
        [createEval](context) {
          const {
            operator,
            operand
          } = this;
          const evaluation = new UnaryConditionEval(operator, false);
          const value = bindOr(context, operand, 1, evaluation.setOperand, evaluation);
          evaluation.reset(value);
          return evaluation;
        }
      }, _class3$o.Operator = UnaryOperator, _class3$o), (_initializer$X = applyDecoratedInitializer(_class2$10.prototype, "operator", [serializable$a], function () {
        return 0;
      }), _initializer2$M = applyDecoratedInitializer(_class2$10.prototype, "operand", [serializable$a], function () {
        return new BindableBoolean();
      })), _class2$10)) || _class$19);
      class UnaryConditionEval {
        constructor(operator, operand) {
          this._operator = operator;
          this._operand = operand;
          this._eval();
        }
        reset(value) {
          this.setOperand(value);
        }
        setOperand(value) {
          this._operand = value;
          this._eval();
        }
        eval() {
          return this._result;
        }
        _eval() {
          const {
            _operand: operand
          } = this;
          switch (this._operator) {
            default:
            case 0:
              this._result = !!operand;
              break;
            case 1:
              this._result = !operand;
              break;
          }
        }
      }

      class TCBinding {}

      const provide = (...valueTypes) => () => {} ;
      const support = transitionSourceFilter => () => {} ;

      var _dec$18, _dec2$V, _class$18, _class2$$, _initializer$W, _initializer2$L;
      const {
        ccclass: ccclass$u,
        serializable: serializable$9
      } = _decorator;
      let TCVariableBinding = (_dec$18 = ccclass$u(`${CLASS_NAME_PREFIX_ANIM}TCVariableBinding`), _dec2$V = provide(0, 3), _dec$18(_class$18 = _dec2$V(_class$18 = (_class2$$ = class TCVariableBinding extends TCBinding {
        constructor(...args) {
          super(...args);
          this.type = _initializer$W && _initializer$W();
          this.variableName = _initializer2$L && _initializer2$L();
        }
        getValueType() {
          return this.type;
        }
        bind(context) {
          const varInstance = context.getVar(this.variableName);
          if (!varInstance) {
            return undefined;
          }
          return new TCVariableBindingEvaluation(varInstance);
        }
      }, (_initializer$W = applyDecoratedInitializer(_class2$$.prototype, "type", [serializable$9, editorOnly], function () {
        return 0;
      }), _initializer2$L = applyDecoratedInitializer(_class2$$.prototype, "variableName", [serializable$9], function () {
        return '';
      })), _class2$$)) || _class$18) || _class$18);
      class TCVariableBindingEvaluation {
        constructor(_varInstance) {
          this._varInstance = _varInstance;
        }
        evaluate() {
          return this._varInstance.value;
        }
      }

      var _dec$17, _dec2$U, _class$17, _class2$_, _initializer$V;
      const {
        ccclass: ccclass$t,
        serializable: serializable$8
      } = _decorator;
      (_dec$17 = ccclass$t(`${CLASS_NAME_PREFIX_ANIM}TCAuxiliaryCurveBinding`), _dec2$U = provide(0), _dec$17(_class$17 = _dec2$U(_class$17 = (_class2$_ = class TCAuxiliaryCurveBinding extends TCBinding {
        constructor(...args) {
          super(...args);
          this.curveName = _initializer$V && _initializer$V();
        }
        getValueType() {
          return 0;
        }
        bind(context) {
          const view = context.getEvaluationTimeAuxiliaryCurveView();
          return new TCAuxiliaryCurveBindingEvaluation(view, this.curveName);
        }
      }, (_initializer$V = applyDecoratedInitializer(_class2$_.prototype, "curveName", [serializable$8], function () {
        return '';
      })), _class2$_)) || _class$17) || _class$17);
      class TCAuxiliaryCurveBindingEvaluation {
        constructor(_view, _curveName) {
          this._view = _view;
          this._curveName = _curveName;
        }
        evaluate() {
          return this._view.get(this._curveName);
        }
      }

      var _dec$16, _dec2$T, _dec3$L, _class$16;
      const {
        ccclass: ccclass$s
      } = _decorator;
      (_dec$16 = ccclass$s(`${CLASS_NAME_PREFIX_ANIM}TCStateWeightBinding`), _dec2$T = provide(0), _dec3$L = support(), _dec$16(_class$16 = _dec2$T(_class$16 = _dec3$L(_class$16 = class TCStateWeightBinding extends TCBinding {
        getValueType() {
          return 0;
        }
        bind(_context) {
          return new TCStateWeightBindingEvaluation();
        }
      }) || _class$16) || _class$16) || _class$16);
      class TCStateWeightBindingEvaluation {
        evaluate(context) {
          return context.sourceStateWeight;
        }
      }

      var _dec$15, _dec2$S, _dec3$K, _class$15;
      const {
        ccclass: ccclass$r
      } = _decorator;
      (_dec$15 = ccclass$r(`${CLASS_NAME_PREFIX_ANIM}TCStateMotionTimeBinding`), _dec2$S = provide(0), _dec3$K = support(), _dec$15(_class$15 = _dec2$S(_class$15 = _dec3$K(_class$15 = class TCStateMotionTimeBinding extends TCBinding {
        getValueType() {
          return 0;
        }
        bind(_context) {
          return new TCStateMotionTimeBindingEvaluation();
        }
      }) || _class$15) || _class$15) || _class$15);
      class TCStateMotionTimeBindingEvaluation {
        evaluate(context) {
          return context.sourceStateMotionTimeNormalized;
        }
      }

      var _dec$14, _class$14, _class2$Z, _initializer$U, _initializer2$K, _initializer3$B, _initializer4$x, _class3$n;
      const {
        ccclass: ccclass$q,
        serializable: serializable$7
      } = _decorator;
      const BinaryOperator = {
        "EQUAL_TO": 0,
        "NOT_EQUAL_TO": 1,
        "LESS_THAN": 2,
        "LESS_THAN_OR_EQUAL_TO": 3,
        "GREATER_THAN": 4,
        "GREATER_THAN_OR_EQUAL_TO": 5
      };
      (_dec$14 = ccclass$q(`${CLASS_NAME_PREFIX_ANIM}BinaryCondition`), _dec$14(_class$14 = (_class2$Z = (_class3$n = class BinaryCondition {
        constructor() {
          this.operator = _initializer$U && _initializer$U();
          this.lhs = _initializer2$K && _initializer2$K();
          this.lhsBinding = _initializer3$B && _initializer3$B();
          this.rhs = _initializer4$x && _initializer4$x();
        }
        clone() {
          const that = new BinaryCondition();
          that.operator = this.operator;
          that.lhs = this.lhs;
          that.lhsBinding = instantiate(this.lhsBinding);
          that.rhs = this.rhs;
          return that;
        }
        [createEval](context) {
          var _this$lhsBinding;
          const lhsBindingEvaluation = (_this$lhsBinding = this.lhsBinding) === null || _this$lhsBinding === void 0 ? void 0 : _this$lhsBinding.bind(context);
          const binaryConditionEval = new BinaryConditionEval(this.operator, this.lhs, this.rhs, lhsBindingEvaluation);
          return binaryConditionEval;
        }
      }, _class3$n.Operator = BinaryOperator, _class3$n), (_initializer$U = applyDecoratedInitializer(_class2$Z.prototype, "operator", [serializable$7], function () {
        return 0;
      }), _initializer2$K = applyDecoratedInitializer(_class2$Z.prototype, "lhs", [serializable$7], function () {
        return 0.0;
      }), _initializer3$B = applyDecoratedInitializer(_class2$Z.prototype, "lhsBinding", [serializable$7], function () {
        return new TCVariableBinding();
      }), _initializer4$x = applyDecoratedInitializer(_class2$Z.prototype, "rhs", [serializable$7], function () {
        return 0.0;
      })), _class2$Z)) || _class$14);
      class BinaryConditionEval {
        constructor(_operator, lhsValue, rhsValue, _lhsBindingEvaluation) {
          this._operator = _operator;
          this._lhsBindingEvaluation = _lhsBindingEvaluation;
          this._lhsValue = lhsValue;
          this._rhsValue = rhsValue;
        }
        eval(context) {
          var _this$_lhsBindingEval, _this$_lhsBindingEval2;
          const 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;
          const rhsValue = this._rhsValue;
          switch (this._operator) {
            default:
            case 0:
              return lhsValue === rhsValue;
            case 1:
              return lhsValue !== rhsValue;
            case 2:
              return lhsValue < rhsValue;
            case 3:
              return lhsValue <= rhsValue;
            case 4:
              return lhsValue > rhsValue;
            case 5:
              return lhsValue >= rhsValue;
          }
        }
      }

      var _dec$13, _class$13, _class2$Y, _initializer$T;
      const {
        ccclass: ccclass$p,
        serializable: serializable$6
      } = _decorator;
      let TriggerCondition = (_dec$13 = ccclass$p(`${CLASS_NAME_PREFIX_ANIM}TriggerCondition`), _dec$13(_class$13 = (_class2$Y = class TriggerCondition {
        constructor() {
          this.trigger = _initializer$T && _initializer$T();
        }
        clone() {
          const that = new TriggerCondition();
          that.trigger = this.trigger;
          return that;
        }
        [createEval](context) {
          const evaluation = new TriggerConditionEval(false);
          const triggerInstance = context.getVar(this.trigger);
          if (validateVariableExistence(triggerInstance, this.trigger)) {
            validateVariableTypeTriggerLike(triggerInstance.type, this.trigger);
            evaluation.setTrigger(triggerInstance.bind(evaluation.setTrigger, evaluation));
          }
          return evaluation;
        }
      }, (_initializer$T = applyDecoratedInitializer(_class2$Y.prototype, "trigger", [serializable$6], function () {
        return '';
      })), _class2$Y)) || _class$13);
      class TriggerConditionEval {
        constructor(triggered) {
          this._triggered = false;
          this._triggered = triggered;
        }
        setTrigger(trigger) {
          this._triggered = trigger;
        }
        eval() {
          return this._triggered;
        }
      }

      var _dec$12, _class$12;
      let StateMachineComponent = (_dec$12 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}StateMachineComponent`), _dec$12(_class$12 = class StateMachineComponent {
        onMotionStateEnter(controller, motionStateStatus) {}
        onMotionStateExit(controller, motionStateStatus) {}
        onMotionStateUpdate(controller, motionStateStatus) {}
        onStateMachineEnter(controller) {}
        onStateMachineExit(controller) {}
      }) || _class$12);

      var _dec$11, _class$11, _class2$X, _initializer$S;
      let MotionSyncInfo = (_dec$11 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}MotionSyncInfo`), _dec$11(_class$11 = (_class2$X = class MotionSyncInfo {
        constructor() {
          this.group = _initializer$S && _initializer$S();
        }
      }, (_initializer$S = applyDecoratedInitializer(_class2$X.prototype, "group", [serializable$l], function () {
        return '';
      })), _class2$X)) || _class$11);

      const POSE_GRAPH_NODE_MENU_PREFIX_POSE = `i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes/`;

      function makeCreateNodeFactory(create_) {
        return {
          listEntries: context => [{
            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: arg => {
            let 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$10, _dec2$R, _dec3$J, _dec4$x, _dec5$v, _dec6$n, _class$10, _class2$W, _initializer$R, _initializer2$J, _descriptor, _descriptor2;
      const ZERO_DURATION_THRESHOLD = 1e-5;
      let PoseNodePlayMotion = (_dec$10 = ccclass$H(`${CLASS_NAME_PREFIX_ANIM}PoseNodePlayMotion`), _dec2$R = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$J = poseGraphCreateNodeFactory(makeCreateNodeFactory(motion => {
        const node = new PoseNodePlayMotion();
        node.motion = motion;
        return node;
      })), _dec4$x = poseGraphNodeAppearance({
        themeColor: '#227F9B'
      }), _dec5$v = input({
        type: 0
      }), _dec6$n = input({
        type: 0
      }), _dec$10(_class$10 = _dec2$R(_class$10 = _dec3$J(_class$10 = _dec4$x(_class$10 = (_class2$W = class PoseNodePlayMotion extends PoseNode {
        constructor(...args) {
          super(...args);
          this.motion = _initializer$R && _initializer$R();
          this.syncInfo = _initializer2$J && _initializer2$J();
          _initializerDefineProperty(this, "startTime", _descriptor, this);
          _initializerDefineProperty(this, "speedMultiplier", _descriptor2, this);
          this._workspace = null;
          this._runtimeSyncRecord = undefined;
        }
        get lastIndicativeWeight() {
          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;
        }
        get elapsedMotionTime() {
          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;
        }
        bind(context) {
          const {
            motion
          } = this;
          if (!motion) {
            return;
          }
          const motionEval = motion[createEval](context, false);
          if (!motionEval) {
            return;
          }
          this._workspace = new Workspace(motionEval, motionEval.createPort());
          if (this.syncInfo.group) {
            this._runtimeSyncRecord = context.motionSyncManager.register(this.syncInfo);
          }
        }
        settle(context) {}
        reenter() {
          if (this._workspace) {
            const {
              _runtimeSyncRecord: runtimeSyncRecord,
              _workspace: {
                motionEval: {
                  duration
                }
              }
            } = this;
            this._forceEvaluateEvaluation();
            const 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;
          }
        }
        doUpdate(context) {
          if (this._workspace) {
            const {
              deltaTime
            } = context;
            const {
              _runtimeSyncRecord: runtimeSyncRecord
            } = this;
            const duration = this._workspace.motionEval.duration;
            let 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;
          }
        }
        doEvaluate(context) {
          if (!this._workspace) {
            return context.pushDefaultedPose();
          } else {
            const normalizedTime = this._runtimeSyncRecord ? this._runtimeSyncRecord.getSyncedEnterTime() : this._workspace.normalizedTime;
            return this._workspace.motionEvalPort.evaluate(normalizedTime, context);
          }
        }
      }, (_initializer$R = applyDecoratedInitializer(_class2$W.prototype, "motion", [serializable$l], function () {
        return new ClipMotion();
      }), _initializer2$J = applyDecoratedInitializer(_class2$W.prototype, "syncInfo", [serializable$l], function () {
        return new MotionSyncInfo();
      }), _descriptor = _applyDecoratedDescriptor(_class2$W.prototype, "startTime", [serializable$l, _dec5$v], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function () {
          return 0.0;
        }
      }), _descriptor2 = _applyDecoratedDescriptor(_class2$W.prototype, "speedMultiplier", [serializable$l, _dec6$n], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function () {
          return 1.0;
        }
      })), _class2$W)) || _class$10) || _class$10) || _class$10) || _class$10);
      class Workspace {
        constructor(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;
      }
      class InstantiatedPoseGraph {
        constructor(_rootPoseNode, _countingPlayMotionNodes) {
          this._rootPoseNode = _rootPoseNode;
          this._countingPlayMotionNodes = _countingPlayMotionNodes;
        }
        bind(context) {
          var _this$_rootPoseNode;
          (_this$_rootPoseNode = this._rootPoseNode) === null || _this$_rootPoseNode === void 0 ? void 0 : _this$_rootPoseNode.bind(context);
        }
        settle(context) {
          var _this$_rootPoseNode2;
          (_this$_rootPoseNode2 = this._rootPoseNode) === null || _this$_rootPoseNode2 === void 0 ? void 0 : _this$_rootPoseNode2.settle(context);
        }
        reenter() {
          var _this$_rootPoseNode3;
          (_this$_rootPoseNode3 = this._rootPoseNode) === null || _this$_rootPoseNode3 === void 0 ? void 0 : _this$_rootPoseNode3.reenter();
        }
        update(context) {
          var _this$_rootPoseNode4;
          (_this$_rootPoseNode4 = this._rootPoseNode) === null || _this$_rootPoseNode4 === void 0 ? void 0 : _this$_rootPoseNode4.update(context);
        }
        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, 1)) !== null && _this$_rootPoseNode$e !== void 0 ? _this$_rootPoseNode$e : null;
        }
        countMotionTime() {
          const {
            _countingPlayMotionNodes: playMotionNodes
          } = this;
          if (!playMotionNodes) {
            {
              assertIsTrue(false, `Should not call countMotionTime() on this pose graph ` + `since "mayCountMotionTime" was not passed to instantiatePoseGraph()`);
            }
            return 0.0;
          }
          let maxWeightedTime = 0.0;
          let maxWeight = Number.NEGATIVE_INFINITY;
          for (let iPlayMotionNode = 0; iPlayMotionNode < playMotionNodes.length; ++iPlayMotionNode) {
            const {
              elapsedMotionTime,
              lastIndicativeWeight
            } = playMotionNodes[iPlayMotionNode];
            if (lastIndicativeWeight > maxWeight) {
              maxWeight = lastIndicativeWeight;
              maxWeightedTime = elapsedMotionTime;
            }
          }
          return maxWeightedTime;
        }
      }
      function instantiatePoseGraph(graph, linkContext, mayCountMotionTime = false) {
        const {
          outputNode
        } = graph;
        const outputNodeShell = graph.getShell(outputNode);
        assertIsTrue(outputNodeShell);
        const bindings = outputNodeShell.getBindings();
        assertIsTrue(bindings.length < 2);
        if (bindings.length === 0) {
          return new InstantiatedPoseGraph(undefined, mayCountMotionTime ? [] : undefined);
        }
        const binding = bindings[0];
        assertIsTrue(binding.outputIndex === 0);
        assertIsTrue(binding.producer instanceof PoseNode);
        const instantiationMap = new Map();
        const mainRecord = instantiateNode(graph, binding.producer, instantiationMap, linkContext);
        assertIsTrue(mainRecord instanceof PoseNode);
        return new InstantiatedPoseGraph(mainRecord, mayCountMotionTime ? Array.from(instantiationMap.values()).filter(node => node instanceof PoseNodePlayMotion) : undefined);
      }
      function instantiateNode(graph, node, instantiationMap, linkContext) {
        const shell = graph.getShell(node);
        assertIsTrue(shell, `Want to instantiate an unbound graph?`);
        const existing = instantiationMap.get(node);
        if (existing) {
          return existing;
        }
        const instantiated = instantiate(node);
        if ('__callOnAfterDeserializeRecursive' in instantiated) {
          instantiated.__callOnAfterDeserializeRecursive();
        }
        if (instantiated instanceof PureValueNode) {
          instantiated.link(linkContext);
        }
        const consumerNode = instantiated;
        const runtimePVNodePropertyBindings = [];
        for (const {
          producer: producerNode,
          outputIndex: producerOutputIndex,
          inputPath: consumerInputPath
        } of shell.getBindings()) {
          if (!isEvaluatableNode(producerNode)) {
            warn(`There's a input bound to a node with unrecognized type.`);
            continue;
          }
          const producer = instantiateNode(graph, producerNode, instantiationMap, linkContext);
          if (producer instanceof PoseNode) {
            assertIsTrue(consumerNode instanceof PoseNode);
            linkPoseNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
          } else {
            const runtimePVNodePropertyBinding = linkPVNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
            if (runtimePVNodePropertyBinding) {
              runtimePVNodePropertyBindings.push(runtimePVNodePropertyBinding);
            }
          }
        }
        const dependencyEvaluation = new DependencyEvaluation(runtimePVNodePropertyBindings);
        let evaluation;
        if (consumerNode instanceof PoseNode) {
          consumerNode._setDependencyEvaluation(dependencyEvaluation);
          evaluation = consumerNode;
        } else {
          const pureValueNodeEvaluation = new RuntimePVNodeEvaluation(consumerNode, dependencyEvaluation);
          evaluation = pureValueNodeEvaluation;
        }
        instantiationMap.set(node, evaluation);
        return evaluation;
      }
      class DependencyEvaluation {
        constructor(bindingEvaluations) {
          this._bindingEvaluations = void 0;
          this._bindingEvaluations = bindingEvaluations;
        }
        evaluate() {
          const {
            _bindingEvaluations: bindingEvaluations
          } = this;
          for (const binding of bindingEvaluations) {
            binding.evaluate();
          }
        }
      }
      class RuntimePVNodeEvaluation {
        constructor(_node, _dependency) {
          this._outputs = void 0;
          this._node = _node;
          this._dependency = _dependency;
          this._outputs = new Array(_node.outputCount);
        }
        get node() {
          return this._node;
        }
        get outputCount() {
          return this._outputs.length;
        }
        getDefaultOutput() {
          return this.getOutput(0);
        }
        getOutput(outputIndex) {
          return this._outputs[outputIndex];
        }
        evaluate() {
          const {
            _node: node,
            _dependency: dependency
          } = this;
          dependency.evaluate();
          node.selfEvaluate(this._outputs);
        }
      }
      function linkPoseNode(consumerNode, consumerInputPath, producerNode, producerOutputIndex) {
        const [consumerPropertyKey, consumerElementIndex = -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;
        }
        const 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;
      }
      class RuntimePVNodePlainPropertyBinding {
        constructor(_consumerNode, _consumerPropertyKey, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey] = this._producerRecord.getOutput(this._producerOutputIndex);
        }
      }
      class RuntimePVNodeArrayElementPropertyBinding {
        constructor(_consumerNode, _consumerPropertyKey, _consumerElementIndex, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._consumerElementIndex = _consumerElementIndex;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey][this._consumerElementIndex] = this._producerRecord.getOutput(this._producerOutputIndex);
        }
      }
      function linkPVNode(consumerNode, consumerInputPath, producerRecord, producerOutputIndex) {
        const [consumerPropertyKey, consumerElementIndex = -1] = consumerInputPath;
        if (!(consumerPropertyKey in consumerNode)) {
          warn(`Invalid binding: consumer node has no property ${consumerPropertyKey}`);
          return undefined;
        }
        const 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);
      }

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

      class RuntimeMotionSyncManager {
        constructor() {
          this._groups = [];
        }
        register(syncInfo) {
          const {
            group: groupName
          } = syncInfo;
          let group = this._groups.find(group => group.name === groupName);
          if (!group) {
            group = new Group(groupName);
            this._groups.push(group);
          }
          return group.addMember();
        }
        sync() {
          for (const group of this._groups) {
            group.sync();
          }
        }
      }
      class Group {
        constructor(name) {
          this._lastLeader = undefined;
          this._records = [];
          this.name = name;
        }
        addMember() {
          const record = new RuntimeMotionSyncRecordImpl();
          this._records.push(record);
          return record;
        }
        sync() {
          const {
            _records: records
          } = this;
          const nRecords = records.length;
          assertIsTrue(nRecords > 0);
          const {
            _lastLeader: lastLeader
          } = this;
          this._lastLeader = undefined;
          if (records.every(r => !r.active)) {
            return;
          }
          records.sort((a, b) => {
            const kA = a.active ? a.weight : -1.0;
            const kB = b.active ? b.weight : -1.0;
            return kB - kA;
          });
          {
            const firstInactiveRecord = records.findIndex(r => !r.active);
            assertIsTrue((firstInactiveRecord < 0 ? [] : records.slice(firstInactiveRecord)).every(r => !r.active));
          }
          let leaderIndex = 0;
          const leaderWeight = records[0].weight;
          if (records[leaderIndex] !== lastLeader) {
            for (let iRecord = 0; iRecord < nRecords; ++iRecord) {
              const 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];
          const leaderNormalizedTime = records[leaderIndex].normalizedTime;
          for (let iRecord = 0; iRecord < nRecords; ++iRecord) {
            const record = records[iRecord];
            if (!record.active) {
              break;
            }
            record.normalizedTime = leaderNormalizedTime;
            record.reset();
          }
        }
      }
      class RuntimeMotionSyncRecordImpl {
        constructor() {
          this.normalizedTime = 0.0;
          this.weight = 0.0;
          this.active = false;
        }
        notifyRenter(normalizedTime) {
          this.reset();
          this.normalizedTime = normalizedTime;
        }
        notifyUpdate(normalizedDeltaTime, weight) {
          this.normalizedTime += normalizedDeltaTime;
          if (this.active) {
            this.weight += weight;
          } else {
            this.active = true;
            this.weight = weight;
          }
        }
        reset() {
          this.active = false;
          this.weight = 0.0;
        }
        getSyncedEnterTime() {
          return this.normalizedTime;
        }
      }

      class RuntimeStashRecord {
        constructor(_allocator) {
          this._state = 0;
          this._instantiatedPoseGraph = undefined;
          this._maxRequestedUpdateTime = 0.0;
          this._evaluationCache = null;
          this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          this._allocator = _allocator;
        }
        set(stash, context) {
          assertIsTrue(this._state === 0, `The stash has already been set.`);
          const instantiatedPoseGraph = instantiatePoseGraph(stash.graph, context);
          instantiatedPoseGraph.bind(context);
          this._instantiatedPoseGraph = instantiatedPoseGraph;
          this._state = 1;
        }
        settle(context) {
          assertIsTrue(this._state === 1 || this._state === 2);
          assertIsTrue(this._instantiatedPoseGraph);
          this._instantiatedPoseGraph.settle(context);
          this._state = 2;
        }
        reset() {
          switch (this._state) {
            case 2:
            case 4:
              break;
            case 3:
              this._state = 4;
              break;
            case 6:
            case 8:
              if (this._evaluationCache) {
                this._allocator.destroyPose(this._evaluationCache);
                this._evaluationCache = null;
              }
              this._maxRequestedUpdateTime = 0.0;
              this._state = 3;
              break;
            case 0:
            default:
              assertIsTrue(false, `Unexpected stash state`);
          }
        }
        reenter() {
          switch (this._state) {
            default:
              assertIsTrue(false, `Unexpected stash state ${this._state} when reenter().`);
              break;
            case 3:
            case 6:
              break;
            case 2:
            case 4:
              {
                this._state = 3;
                assertIsTrue(this._instantiatedPoseGraph);
                this._instantiatedPoseGraph.reenter();
                break;
              }
          }
        }
        requestUpdate(context) {
          const {
            deltaTime
          } = context;
          assertIsTrue(this._state === 4 || this._state === 3 || this._state === 5 || this._state === 6);
          assertIsTrue(this._instantiatedPoseGraph);
          if (this._state === 5) {
            return;
          }
          const diffDeltaTime = Math.max(0.0, deltaTime - this._maxRequestedUpdateTime);
          if (this._state === 6) {
            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 = 5;
          this._maxRequestedUpdateTime = Math.max(deltaTime, this._maxRequestedUpdateTime);
          const updateContext = this._updateContextGenerator.generate(diffDeltaTime, context.indicativeWeight);
          this._instantiatedPoseGraph.update(updateContext);
          this._state = 6;
        }
        evaluate(context) {
          switch (this._state) {
            default:
              assertIsTrue(false, `Unexpected stash state ${this._state} when evaluate().`);
              break;
            case 7:
              this._state = 8;
              break;
            case 8:
              break;
            case 6:
              {
                var _this$_instantiatedPo;
                assertIsTrue(!this._evaluationCache);
                this._state = 7;
                const pose = (_this$_instantiatedPo = this._instantiatedPoseGraph) === null || _this$_instantiatedPo === void 0 ? void 0 : _this$_instantiatedPo.evaluate(context);
                this._state = 8;
                if (pose) {
                  const heapPose = this._allocator.allocatePose();
                  heapPose.transforms.set(pose.transforms);
                  heapPose.auxiliaryCurves.set(pose.auxiliaryCurves);
                  this._evaluationCache = heapPose;
                  context.popPose();
                }
                this._state = 8;
                break;
              }
          }
          assertIsTrue(this._state === 8);
          assertIsTrue(this._instantiatedPoseGraph);
          return this._evaluationCache ? context.pushDuplicatedPose(this._evaluationCache) : null;
        }
      }
      class RuntimeStashManager {
        constructor(allocator) {
          this._allocator = void 0;
          this._stashEvaluations = {};
          this._allocator = allocator;
        }
        bindStash(id) {
          return this._stashEvaluations[id];
        }
        getStash(id) {
          return this._stashEvaluations[id];
        }
        addStash(id) {
          this._stashEvaluations[id] = new RuntimeStashRecord(this._allocator);
        }
        setStash(id, stash, context) {
          assertIsTrue(id in this._stashEvaluations);
          this._stashEvaluations[id].set(stash, context);
        }
        reset() {
          for (const stashId in this._stashEvaluations) {
            const record = this._stashEvaluations[stashId];
            record.reset();
          }
        }
        settle(context) {
          for (const stashId in this._stashEvaluations) {
            const record = this._stashEvaluations[stashId];
            record.settle(context);
          }
        }
      }

      class DefaultTopLevelPoseNode extends PoseNode {
        constructor(graph, bindingContext, poseStashAllocator) {
          super();
          this._layerRecords = void 0;
          const layerEvaluationRecords = graph.layers.map(layer => {
            const record = new LayerEvaluationRecord(layer, bindingContext, poseStashAllocator);
            return record;
          });
          this._layerRecords = layerEvaluationRecords;
        }
        get layerCount() {
          return this._layerRecords.length;
        }
        reenter() {}
        bind(_context) {}
        settle(context) {
          const {
            _layerRecords: layerRecords
          } = this;
          const nLayers = layerRecords.length;
          for (let iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].settle(context);
          }
        }
        getLayerWeight(layerIndex) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, `Invalid layer index`);
          return this._layerRecords[layerIndex].weight;
        }
        setLayerWeight(layerIndex, weight) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, `Invalid layer index`);
          this._layerRecords[layerIndex].weight = weight;
        }
        getLayerTopLevelStateMachineEvaluation(layerIndex) {
          return this._layerRecords[layerIndex].stateMachineEvaluation;
        }
        overrideClips(context) {
          const {
            _layerRecords: layerRecords
          } = this;
          const nLayers = layerRecords.length;
          for (let iLayer = 0; iLayer < nLayers; ++iLayer) {
            const layerRecord = layerRecords[iLayer];
            context._pushAdditiveFlag(layerRecord.additive);
            layerRecord.stateMachineEvaluation.overrideClips(context);
            context._popAdditiveFlag();
          }
        }
        doUpdate(context) {
          const {
            _layerRecords: layerRecords
          } = this;
          const nLayers = layerRecords.length;
          for (let iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].update(context);
          }
        }
        doEvaluate(context) {
          const finalPose = context.pushDefaultedPose();
          const {
            _layerRecords: layerRecords
          } = this;
          const nLayers = layerRecords.length;
          for (let iLayer = 0; iLayer < nLayers; ++iLayer) {
            const layer = layerRecords[iLayer];
            const layerPose = layer.stateMachineEvaluation.evaluate(context);
            const layerActualWeight = layer.weight * layer.stateMachineEvaluation.passthroughWeight;
            const {
              transformFilter
            } = layer;
            if (layer.additive) {
              applyDeltaPose(finalPose, layerPose, layerActualWeight, transformFilter);
            } else {
              blendPoseInto(finalPose, layerPose, layerActualWeight, transformFilter);
            }
            context.popPose();
            layer.postEvaluate();
          }
          return finalPose;
        }
      }
      class LayerEvaluationRecord {
        constructor(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;
          const stashManager = new RuntimeStashManager(poseStashAllocator);
          for (const [stashId, _] of layer.stashes()) {
            stashManager.addStash(stashId);
          }
          this._stashManager = stashManager;
          const motionSyncManager = new RuntimeMotionSyncManager();
          this._motionSyncManager = motionSyncManager;
          bindingContext._setLayerWideContextProperties(stashManager, motionSyncManager);
          for (const [stashId, stash] of layer.stashes()) {
            stashManager.setStash(stashId, stash, bindingContext);
          }
          this.weight = layer.weight;
          const 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();
        }
        get stateMachineEvaluation() {
          return this._topLevelStateMachineEval;
        }
        settle(context) {
          if (this._mask) {
            this.transformFilter = context.createTransformFilter(this._mask);
          }
          this._stashManager.settle(context);
          this._topLevelStateMachineEval.settle(context);
        }
        update(context) {
          this.stateMachineEvaluation.update(context);
          this._motionSyncManager.sync();
        }
        postEvaluate() {
          this._stashManager.reset();
        }
      }

      class AnimationGraphEval {
        constructor(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 (const [name, variable] of graph.variables) {
            const varInstance = variable[createInstanceTag]();
            this._varInstances[name] = varInstance;
            if (varInstance instanceof VarInstanceTrigger) {
              if (varInstance.resetMode === 1) {
                this._hasAutoTrigger = true;
              }
            }
          }
          const poseLayoutMaintainer = new AnimationGraphPoseLayoutMaintainer(root, this._auxiliaryCurveRegistry);
          this._poseLayoutMaintainer = poseLayoutMaintainer;
          const bindingContext = new AnimationGraphBindingContext(root, poseLayoutMaintainer, this._varInstances, controller);
          bindingContext._setClipOverrides(clipOverrides !== null && clipOverrides !== void 0 ? clipOverrides : undefined);
          this._bindingContext = bindingContext;
          const settleContext = new AnimationGraphSettleContext(poseLayoutMaintainer);
          this._settleContext = settleContext;
          poseLayoutMaintainer.startBind();
          const poseStashAllocator = new DeferredPoseStashAllocator();
          this._poseStashAllocator = poseStashAllocator;
          this._rootPoseNode = new DefaultTopLevelPoseNode(graph, bindingContext, poseStashAllocator);
          this._root = root;
          this._initializeContexts();
        }
        destroy() {
          this._evaluationContext.destroy();
        }
        _destroyAfterException_debugging() {
          const stackSize = this._evaluationContext._stackSize_debugging;
          if (stackSize !== 0) {
            for (let i = 0; i < stackSize; ++i) {
              this._evaluationContext.popPose();
            }
          }
          this._evaluationContext.destroy();
        }
        get layerCount() {
          return this._rootPoseNode.layerCount;
        }
        update(deltaTime) {
          const {
            _evaluationContext: evaluationContext,
            _poseLayoutMaintainer: poseLayoutMaintainer,
            _rootUpdateContextGenerator: rootUpdateContextGenerator,
            _rootPoseNode: rootPoseNode
          } = this;
          const updateContext = rootUpdateContextGenerator.generate(deltaTime, 1.0);
          rootPoseNode.update(updateContext);
          const finalPose = rootPoseNode.evaluate(evaluationContext, 1);
          if (this._hasAutoTrigger) {
            const {
              _varInstances: varInstances
            } = this;
            for (const varName in varInstances) {
              const varInstance = varInstances[varName];
              if (varInstance instanceof VarInstanceTrigger && varInstance.resetMode === 1) {
                varInstance.value = false;
              }
            }
          }
          poseLayoutMaintainer.apply(finalPose);
          evaluationContext.popPose();
          {
            assertIsTrue(evaluationContext.allocatedPoseCount === 0, `Pose leaked.`);
            assertIsTrue(this._poseStashAllocator.allocatedPoseCount === 0, `Pose leaked.`);
          }
        }
        getVariables() {
          return Object.entries(this._varInstances);
        }
        getCurrentStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentStateStatus();
        }
        getCurrentClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentClipStatuses();
        }
        getCurrentTransition(layer) {
          const {
            _currentTransitionCache: currentTransition
          } = this;
          const isInTransition = this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentTransition(currentTransition);
          return isInTransition ? currentTransition : null;
        }
        getNextStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextStateStatus();
        }
        getNextClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextClipStatuses();
        }
        getValue(name) {
          const varInstance = this._varInstances[name];
          if (!varInstance) {
            return undefined;
          } else {
            return varInstance.value;
          }
        }
        setValue(name, value) {
          const varInstance = this._varInstances[name];
          if (!varInstance) {
            return;
          }
          varInstance.value = value;
        }
        getLayerWeight(layerIndex) {
          return this._rootPoseNode.getLayerWeight(layerIndex);
        }
        setLayerWeight(layerIndex, weight) {
          this._rootPoseNode.setLayerWeight(layerIndex, weight);
        }
        overrideClips(overrides) {
          const {
            _poseLayoutMaintainer: poseLayoutMaintainer
          } = this;
          poseLayoutMaintainer.startBind();
          this._bindingContext._setClipOverrides(overrides);
          this._rootPoseNode.overrideClips(this._bindingContext);
          this._updateAfterPossiblePoseLayoutChange();
        }
        getAuxiliaryCurveValue(curveName) {
          return this._auxiliaryCurveRegistry.get(curveName);
        }
        _initializeContexts() {
          const {
            _poseLayoutMaintainer: poseLayoutMaintainer
          } = this;
          void poseLayoutMaintainer.endBind();
          this._createOrUpdateTransformFilters();
          const evaluationContext = poseLayoutMaintainer.createEvaluationContext();
          this._evaluationContext = evaluationContext;
          poseLayoutMaintainer.fetchDefaultTransforms(evaluationContext[defaultTransformsTag]);
          poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
        }
        _updateAfterPossiblePoseLayoutChange() {
          const {
            _poseLayoutMaintainer: poseLayoutMaintainer
          } = this;
          const layoutChangeFlags = poseLayoutMaintainer.endBind();
          if (layoutChangeFlags === 0) {
            return;
          }
          if (layoutChangeFlags & 1 || layoutChangeFlags & 2) {
            this._createOrUpdateTransformFilters();
          }
          let evaluationContextRecreated = false;
          if (layoutChangeFlags & 1 || layoutChangeFlags & 4) {
            const evaluationContext = poseLayoutMaintainer.createEvaluationContext();
            this._evaluationContext.destroy();
            this._evaluationContext = evaluationContext;
            evaluationContextRecreated = true;
            poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
          }
          if (evaluationContextRecreated || layoutChangeFlags & 1 || layoutChangeFlags & 2) {
            poseLayoutMaintainer.fetchDefaultTransforms(this._evaluationContext[defaultTransformsTag]);
          }
        }
        _createOrUpdateTransformFilters() {
          this._rootPoseNode.settle(this._settleContext);
        }
      }

      var _dec$$, _dec2$Q, _dec3$I, _class$$, _class2$V, _initializer$Q;
      const {
        ccclass: ccclass$o,
        menu: menu$e,
        help: help$2,
        type: type$6,
        serializable: serializable$5,
        editable: editable$4,
        formerlySerializedAs: formerlySerializedAs$1
      } = _decorator;
      let AnimationController = (_dec$$ = ccclass$o('cc.animation.AnimationController'), _dec2$Q = type$6(AnimationGraphLike), _dec3$I = formerlySerializedAs$1('graph'), _dec$$(_class$$ = (_class2$V = class AnimationController extends Component {
        constructor(...args) {
          super(...args);
          this._graph = _initializer$Q && _initializer$Q();
          this._graphEval = null;
        }
        get graph() {
          return this._graph;
        }
        set graph(value) {
          this._graph = value;
        }
        get layerCount() {
          var _this$_graphEval$laye, _this$_graphEval;
          return (_this$_graphEval$laye = (_this$_graphEval = this._graphEval) === null || _this$_graphEval === void 0 ? void 0 : _this$_graphEval.layerCount) !== null && _this$_graphEval$laye !== void 0 ? _this$_graphEval$laye : 0;
        }
        __preload() {
          const {
            graph
          } = this;
          if (graph) {
            let originalGraph;
            let clipOverrides = null;
            if (graph instanceof AnimationGraphVariant) {
              if (!graph.original) {
                return;
              }
              originalGraph = graph.original;
              clipOverrides = graph.clipOverrides;
            } else {
              assertIsTrue(graph instanceof AnimationGraph);
              originalGraph = graph;
            }
            const graphEval = new AnimationGraphEval(originalGraph, this.node, this, clipOverrides);
            this._graphEval = graphEval;
          }
        }
        onDestroy() {
          var _this$_graphEval2;
          (_this$_graphEval2 = this._graphEval) === null || _this$_graphEval2 === void 0 ? void 0 : _this$_graphEval2.destroy();
        }
        update(deltaTime) {
          var _this$_graphEval3;
          (_this$_graphEval3 = this._graphEval) === null || _this$_graphEval3 === void 0 ? void 0 : _this$_graphEval3.update(deltaTime);
        }
        getVariables() {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getVariables();
        }
        setValue(name, value) {
          return this.setValue_experimental(name, value);
        }
        setValue_experimental(name, value) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          graphEval.setValue(name, value);
        }
        getValue(name) {
          const 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;
          }
        }
        getValue_experimental(name) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getValue(name);
        }
        getCurrentStateStatus(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentStateStatus(layer);
        }
        getCurrentClipStatuses(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentClipStatuses(layer);
        }
        getCurrentTransition(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentTransition(layer);
        }
        getNextStateStatus(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getNextStateStatus(layer);
        }
        getNextClipStatuses(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getNextClipStatuses(layer);
        }
        getLayerWeight(layer) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.getLayerWeight(layer);
        }
        setLayerWeight(layer, weight) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          return graphEval.setLayerWeight(layer, weight);
        }
        overrideClips_experimental(overrides) {
          const {
            _graphEval: graphEval
          } = this;
          assertIsNonNullable(graphEval);
          graphEval.overrideClips(overrides);
        }
        getAuxiliaryCurveValue_experimental(curveName) {
          const {
            _graphEval: graphEval
          } = this;
          if (!graphEval) {
            return 0.0;
          }
          return graphEval.getAuxiliaryCurveValue(curveName);
        }
      }, (_applyDecoratedDescriptor(_class2$V.prototype, "graph", [_dec2$Q], Object.getOwnPropertyDescriptor(_class2$V.prototype, "graph"), _class2$V.prototype), _initializer$Q = applyDecoratedInitializer(_class2$V.prototype, "_graph", [serializable$5, _dec3$I], function () {
        return null;
      })), _class2$V)) || _class$$);

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

      class BlendStateBuffer {
        constructor() {
          this._nodeBlendStates = new Map();
        }
        createWriter(node, property, host, constants) {
          const propertyBlendState = this.ref(node, property);
          return new BlendStateWriterInternal(node, property, propertyBlendState, host, constants);
        }
        destroyWriter(writer) {
          const internal = writer;
          this.deRef(internal.node, internal.property);
        }
        ref(node, property) {
          let nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            nodeBlendState = this.createNodeBlendState();
            this._nodeBlendStates.set(node, nodeBlendState);
          }
          const propertyBlendState = nodeBlendState.refProperty(node, property);
          return propertyBlendState;
        }
        deRef(node, property) {
          const nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            return;
          }
          nodeBlendState.deRefProperty(property);
          if (nodeBlendState.empty) {
            this._nodeBlendStates.delete(node);
          }
        }
        apply() {
          this._nodeBlendStates.forEach((nodeBlendState, node) => {
            nodeBlendState.apply(node);
          });
        }
      }
      class BlendStateWriterInternal {
        constructor(_node, _property, _propertyBlendState, _host, _constants) {
          this._node = _node;
          this._property = _property;
          this._propertyBlendState = _propertyBlendState;
          this._host = _host;
          this._constants = _constants;
        }
        get node() {
          return this._node;
        }
        get property() {
          return this._property;
        }
        getValue() {
          return this._node[this._property];
        }
        setValue(value) {
          const {
            _propertyBlendState: propertyBlendState,
            _host: host
          } = this;
          const weight = host.weight;
          propertyBlendState.blend(value, weight);
        }
      }
      class LegacyVec3PropertyBlendState {
        constructor() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Vec3();
        }
        blend(value, weight) {
          this.accumulatedWeight = mixAveragedVec3(this.result, this.result, this.accumulatedWeight, value, weight);
        }
        reset() {
          this.accumulatedWeight = 0.0;
          Vec3.zero(this.result);
        }
      }
      class LegacyQuatPropertyBlendState {
        constructor() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Quat();
        }
        blend(value, weight) {
          this.accumulatedWeight = mixAveragedQuat(this.result, this.result, this.accumulatedWeight, value, weight);
        }
        reset() {
          this.accumulatedWeight = 0.0;
          Quat.identity(this.result);
        }
      }
      class NodeBlendState {
        constructor() {
          this._transformApplyFlags = 0;
          this._properties = {};
        }
        get empty() {
          const {
            _properties: properties
          } = this;
          return !properties.position && !properties.rotation && !properties.eulerAngles && !properties.scale;
        }
        refProperty(node, property) {
          var _properties$property, _properties$property2;
          const {
            _properties: properties
          } = this;
          let 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;
        }
        deRefProperty(property) {
          const {
            _properties: properties
          } = this;
          const propertyBlendState = properties[property];
          if (!propertyBlendState) {
            return;
          }
          --propertyBlendState.refCount;
          if (propertyBlendState.refCount > 0) {
            return;
          }
          delete properties[property];
        }
        apply(node) {
          const {
            _transformApplyFlags: transformApplyFlags,
            _properties: {
              position,
              scale,
              rotation,
              eulerAngles
            }
          } = this;
          if (!transformApplyFlags) {
            return;
          }
          let t;
          let s;
          let r;
          if (position && transformApplyFlags & 1) {
            t = position.result;
          }
          if (scale && transformApplyFlags & 4) {
            s = scale.result;
          }
          if (eulerAngles && transformApplyFlags & 8) {
            r = eulerAngles.result;
          }
          if (rotation && transformApplyFlags & 2) {
            r = rotation.result;
          }
          if (r || t || s) {
            node.setRTS(r, t, s);
          }
          this._transformApplyFlags = 0;
        }
      }
      class LegacyNodeBlendState extends NodeBlendState {
        apply(node) {
          const {
            _properties: {
              position,
              scale,
              rotation,
              eulerAngles
            }
          } = this;
          if (position && position.accumulatedWeight) {
            this._transformApplyFlags |= 1;
            if (position.accumulatedWeight < 1.0) {
              position.blend(node.position, 1.0 - position.accumulatedWeight);
            }
          }
          if (scale && scale.accumulatedWeight) {
            this._transformApplyFlags |= 4;
            if (scale.accumulatedWeight < 1.0) {
              scale.blend(node.scale, 1.0 - scale.accumulatedWeight);
            }
          }
          if (eulerAngles && eulerAngles.accumulatedWeight) {
            this._transformApplyFlags |= 8;
            if (eulerAngles.accumulatedWeight < 1.0) {
              eulerAngles.blend(node.eulerAngles, 1.0 - eulerAngles.accumulatedWeight);
            }
          }
          if (rotation && rotation.accumulatedWeight) {
            this._transformApplyFlags |= 2;
            if (rotation.accumulatedWeight < 1.0) {
              rotation.blend(node.rotation, 1.0 - rotation.accumulatedWeight);
            }
          }
          super.apply(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();
        }
        _createVec3BlendState(_currentValue) {
          return new LegacyVec3PropertyBlendState();
        }
        _createQuatBlendState(_currentValue) {
          return new LegacyQuatPropertyBlendState();
        }
      }
      class LegacyBlendStateBuffer extends BlendStateBuffer {
        createNodeBlendState() {
          return new LegacyNodeBlendState();
        }
      }
      function mixAveragedVec3(result, previous, accumulatedWeight, input, weight) {
        const newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Vec3.copy(result, input);
        } else if (newSum) {
          const t = weight / newSum;
          Vec3.lerp(result, result, input, t);
        }
        return newSum;
      }
      function mixAveragedQuat(result, previous, accumulatedWeight, input, weight) {
        const newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Quat.copy(result, input);
        } else if (newSum) {
          const t = weight / newSum;
          Quat.slerp(result, previous, input, t);
        }
        return newSum;
      }

      const stack = [];
      const pool$1 = new Map();
      function getWorldMatrix(transform, stamp) {
        let i = 0;
        let 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;
          const 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) {
        let joint = null;
        let i = 0;
        while (node !== root) {
          const id = node.uuid;
          if (pool$1.has(id)) {
            joint = pool$1.get(id);
            break;
          } else {
            joint = {
              node,
              local: new Mat4(),
              world: new Mat4(),
              stamp: -1,
              parent: null
            };
            pool$1.set(id, joint);
          }
          stack[i++] = joint;
          node = node.parent;
          joint = null;
        }
        let child;
        while (i > 0) {
          child = stack[--i];
          stack[i] = null;
          child.parent = joint;
          joint = child;
        }
        return joint;
      }
      function deleteTransform(node) {
        let transform = pool$1.get(node.uuid) || null;
        while (transform) {
          pool$1.delete(transform.node.uuid);
          transform = transform.parent;
        }
      }

      var _class$_, _class2$U;
      let AnimationManager = exports("AnimationManager", ccclass$H(_class$_ = (_class2$U = class AnimationManager extends System {
        constructor(...args) {
          super(...args);
          this._anims = new MutableForwardIterator([]);
          this._crossFades = new MutableForwardIterator([]);
          this._delayEvents = [];
          this._blendStateBuffer = new LegacyBlendStateBuffer();
          this._sockets = [];
        }
        get blendState() {
          return this._blendStateBuffer;
        }
        addCrossFade(crossFade) {
          const index = this._crossFades.array.indexOf(crossFade);
          if (index === -1) {
            this._crossFades.push(crossFade);
          }
        }
        removeCrossFade(crossFade) {
          const index = this._crossFades.array.indexOf(crossFade);
          if (index >= 0) {
            this._crossFades.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        }
        update(dt) {
          const {
            _delayEvents,
            _crossFades: crossFadesIter,
            _sockets
          } = this;
          {
            const crossFades = crossFadesIter.array;
            for (crossFadesIter.i = 0; crossFadesIter.i < crossFades.length; ++crossFadesIter.i) {
              const crossFade = crossFades[crossFadesIter.i];
              crossFade.update(dt);
            }
          }
          const iterator = this._anims;
          const array = iterator.array;
          for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
            const anim = array[iterator.i];
            if (!anim.isMotionless) {
              anim.update(dt);
            }
          }
          this._blendStateBuffer.apply();
          const stamp = director.getTotalFrames();
          for (let i = 0, l = _sockets.length; i < l; i++) {
            const {
              target,
              transform
            } = _sockets[i];
            target.matrix = getWorldMatrix(transform, stamp);
          }
          for (let i = 0, l = _delayEvents.length; i < l; i++) {
            const event = _delayEvents[i];
            event.fn.apply(event.thisArg, event.args);
          }
          _delayEvents.length = 0;
        }
        destruct() {}
        addAnimation(anim) {
          const index = this._anims.array.indexOf(anim);
          if (index === -1) {
            this._anims.push(anim);
          }
        }
        removeAnimation(anim) {
          const index = this._anims.array.indexOf(anim);
          if (index >= 0) {
            this._anims.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        }
        pushDelayEvent(fn, thisArg, args) {
          this._delayEvents.push({
            fn,
            thisArg,
            args
          });
        }
        addSockets(root, sockets) {
          for (let i = 0; i < sockets.length; ++i) {
            const socket = sockets[i];
            if (this._sockets.find(s => s.target === socket.target)) {
              continue;
            }
            const targetNode = root.getChildByPath(socket.path);
            const transform = socket.target && targetNode && getTransform(targetNode, root);
            if (transform) {
              this._sockets.push({
                target: socket.target,
                transform
              });
            }
          }
        }
        removeSockets(root, sockets) {
          for (let i = 0; i < sockets.length; ++i) {
            const socketToRemove = sockets[i];
            for (let j = 0; j < this._sockets.length; ++j) {
              const 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;
              }
            }
          }
        }
      }, _class2$U.ID = 'animation', _class2$U)) || _class$_);
      director.on("director_init", () => {
        const animationManager = new AnimationManager();
        director.registerSystem(AnimationManager.ID, animationManager, System.Priority.HIGH);
      });
      cclegacy.AnimationManager = AnimationManager;

      class CrossFade extends Playable {
        constructor(scheduler) {
          super();
          this._managedStates = [];
          this._fadings = [];
          this._scheduled = false;
          this._scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : getGlobalAnimationManager();
        }
        update(deltaTime) {
          if (this.isMotionless) {
            return;
          }
          const managedStates = this._managedStates;
          const fadings = this._fadings;
          if (managedStates.length === 1 && fadings.length === 1) {
            const state = managedStates[0].state;
            if (state) {
              state.weight = 1.0;
            }
          } else {
            this._calculateWeights(deltaTime);
          }
          if (managedStates.length === 1 && fadings.length === 1) {
            this._unscheduleThis();
          }
        }
        crossFade(state, duration) {
          var _target$state;
          if (this._managedStates.length === 0) {
            duration = 0;
          }
          if (duration === 0) {
            this.clear();
          }
          let target = this._managedStates.find(weightedState => weightedState.state === state);
          if (!target) {
            target = {
              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
          });
          if (!this.isMotionless) {
            this._scheduleThis();
          }
        }
        clear() {
          for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            const state = this._managedStates[iManagedState].state;
            if (state) {
              state.stop();
            }
          }
          this._managedStates.length = 0;
          this._fadings.length = 0;
        }
        onPlay() {
          super.onPlay();
          this._scheduleThis();
        }
        onPause() {
          super.onPause();
          for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            const state = this._managedStates[iManagedState].state;
            if (state) {
              state.pause();
            }
          }
          this._unscheduleThis();
        }
        onResume() {
          super.onResume();
          for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            const state = this._managedStates[iManagedState].state;
            if (state) {
              state.resume();
            }
          }
          this._scheduleThis();
        }
        onStop() {
          super.onStop();
          this.clear();
        }
        _calculateWeights(deltaTime) {
          const managedStates = this._managedStates;
          const fadings = this._fadings;
          for (let iManagedState = 0; iManagedState < managedStates.length; ++iManagedState) {
            const state = managedStates[iManagedState].state;
            if (state) {
              state.weight = 0;
            }
          }
          let absoluteWeight = 1.0;
          let deadFadingBegin = fadings.length;
          for (let iFading = 0; iFading < fadings.length; ++iFading) {
            const fading = fadings[iFading];
            fading.easeTime += deltaTime;
            const relativeWeight = fading.easeDuration === 0 ? 1 : clamp01(fading.easeTime / fading.easeDuration);
            const 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 (let iDeadFading = deadFadingBegin; iDeadFading < fadings.length; ++iDeadFading) {
              const 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);
          }
        }
        _scheduleThis() {
          if (!this._scheduled) {
            this._scheduler.addCrossFade(this);
            this._scheduled = true;
          }
        }
        _unscheduleThis() {
          if (this._scheduled) {
            this._scheduler.removeCrossFade(this);
            this._scheduled = false;
          }
        }
      }

      var _dec$_, _dec2$P, _dec3$H, _dec4$w, _dec5$u, _class$Z, _class2$T, _initializer$P, _initializer2$I, _initializer3$A, _class3$m;
      let Animation$2 = (_dec$_ = ccclass$H('cc.Animation'), _dec2$P = executionOrder$1(99), _dec3$H = type$a([AnimationClip]), _dec4$w = type$a(AnimationClip), _dec5$u = type$a([AnimationClip]), _dec$_(_class$Z = _dec2$P(_class$Z = (_class2$T = (_class3$m = class Animation extends Eventify(Component) {
        constructor(...args) {
          super(...args);
          this.playOnLoad = _initializer$P && _initializer$P();
          this._crossFade = new CrossFade();
          this._nameToState = createMap(true);
          this._clips = _initializer2$I && _initializer2$I();
          this._defaultClip = _initializer3$A && _initializer3$A();
          this._hasBeenPlayed = false;
        }
        get clips() {
          return this._clips;
        }
        set clips(value) {
          if (this._crossFade) {
            this._crossFade.clear();
          }
          for (const clip of this._clips) {
            if (clip) {
              this._removeStateOfAutomaticClip(clip);
            }
          }
          for (const clip of value) {
            if (clip) {
              this.createState(clip);
            }
          }
          const newDefaultClip = value.find(clip => equalClips(clip, this._defaultClip));
          if (newDefaultClip) {
            this._defaultClip = newDefaultClip;
          } else {
            this._defaultClip = null;
          }
          this._clips = value;
        }
        get defaultClip() {
          return this._defaultClip;
        }
        set defaultClip(value) {
          this._defaultClip = value;
          if (!value) {
            return;
          }
          const isBoundedDefaultClip = this._clips.findIndex(clip => equalClips(clip, value)) >= 0;
          if (!isBoundedDefaultClip) {
            this._clips.push(value);
            this.createState(value);
          }
        }
        onLoad() {
          this.clips = this._clips;
          for (const stateName in this._nameToState) {
            const state = this._nameToState[stateName];
            state.initialize(this.node);
          }
        }
        start() {
          if (this.playOnLoad && !this._hasBeenPlayed && this._defaultClip) {
            this.crossFade(this._defaultClip.name, 0);
          }
        }
        onEnable() {
          this._crossFade.resume();
        }
        onDisable() {
          this._crossFade.pause();
        }
        onDestroy() {
          this._crossFade.stop();
          for (const name in this._nameToState) {
            const state = this._nameToState[name];
            state.destroy();
          }
          this._nameToState = createMap(true);
        }
        play(name) {
          this._hasBeenPlayed = true;
          if (!name) {
            if (!this._defaultClip) {
              return;
            }
            name = this._defaultClip.name;
          }
          this.crossFade(name, 0);
        }
        crossFade(name, duration = 0.3) {
          this._hasBeenPlayed = true;
          const state = this._nameToState[name];
          if (state) {
            this.doPlayOrCrossFade(state, duration);
          }
        }
        pause() {
          this._crossFade.pause();
        }
        resume() {
          this._crossFade.resume();
        }
        stop() {
          this._crossFade.stop();
        }
        getState(name) {
          const state = this._nameToState[name];
          if (state && !state.curveLoaded) {
            state.initialize(this.node);
          }
          return state || null;
        }
        createState(clip, name) {
          name = name || clip.name;
          this.removeState(name);
          return this._doCreateState(clip, name);
        }
        removeState(name) {
          const state = this._nameToState[name];
          if (state) {
            state.allowLastFrameEvent(false);
            state.stop();
            delete this._nameToState[name];
          }
        }
        addClip(clip, name) {
          if (!contains$2(this._clips, clip)) {
            this._clips.push(clip);
          }
          return this.createState(clip, name);
        }
        removeClip(clip, force) {
          let removalState;
          for (const name in this._nameToState) {
            const state = this._nameToState[name];
            const 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(item => item !== clip);
          if (removalState) {
            delete this._nameToState[removalState.name];
          }
        }
        on(type, callback, thisArg, once) {
          const ret = super.on(type, callback, thisArg, once);
          if (type === "lastframe") {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        }
        once(type, callback, thisArg) {
          const ret = super.once(type, callback, thisArg);
          if (type === "lastframe") {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        }
        off(type, callback, thisArg) {
          super.off(type, callback, thisArg);
          if (type === "lastframe") {
            this._syncDisallowLastFrameEvent();
          }
        }
        _createState(clip, name) {
          return new AnimationState$1(clip, name);
        }
        _doCreateState(clip, name) {
          const state = this._createState(clip, name);
          state._setEventTarget(this);
          state.allowLastFrameEvent(this.hasEventListener("lastframe"));
          if (this.node) {
            state.initialize(this.node);
          }
          this._nameToState[state.name] = state;
          return state;
        }
        doPlayOrCrossFade(state, duration) {
          this._crossFade.play();
          this._crossFade.crossFade(state, duration);
        }
        _removeStateOfAutomaticClip(clip) {
          for (const name in this._nameToState) {
            const state = this._nameToState[name];
            if (equalClips(clip, state.clip)) {
              state.stop();
              delete this._nameToState[name];
            }
          }
        }
        _syncAllowLastFrameEvent() {
          if (this.hasEventListener("lastframe")) {
            for (const stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(true);
            }
          }
        }
        _syncDisallowLastFrameEvent() {
          if (!this.hasEventListener("lastframe")) {
            for (const stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(false);
            }
          }
        }
      }, _class3$m.EventType = AnimationStateEventType, _class3$m), (_applyDecoratedDescriptor(_class2$T.prototype, "clips", [_dec3$H], Object.getOwnPropertyDescriptor(_class2$T.prototype, "clips"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "defaultClip", [_dec4$w], Object.getOwnPropertyDescriptor(_class2$T.prototype, "defaultClip"), _class2$T.prototype), _initializer$P = applyDecoratedInitializer(_class2$T.prototype, "playOnLoad", [serializable$l], function () {
        return false;
      }), _initializer2$I = applyDecoratedInitializer(_class2$T.prototype, "_clips", [_dec5$u], function () {
        return [];
      }), _initializer3$A = applyDecoratedInitializer(_class2$T.prototype, "_defaultClip", [serializable$l], function () {
        return null;
      })), _class2$T)) || _class$Z) || _class$Z); exports({ Animation: Animation$2, AnimationComponent: Animation$2 });
      function equalClips(clip1, clip2) {
        if (clip1 === clip2) {
          return true;
        }
        return !!clip1 && !!clip2 && clip1._uuid === clip2._uuid && clip1._uuid;
      }
      cclegacy.Animation = Animation$2;
      cclegacy.AnimationComponent = Animation$2;
      setClassAlias(Animation$2, 'cc.AnimationComponent');

      const m4_1$3 = new Mat4();
      function getPathFromRoot(target, root) {
        let node = target;
        let 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$3, target.rotation, target.position, target.scale);
          Mat4.multiply(outMatrix, m4_1$3, outMatrix);
          target = target.parent;
        }
        return outMatrix;
      }

      let 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 = {}));
      let 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 = {}));
      let 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 = {}));
      class AudioPCMDataView {
        constructor(...args) {
          this._bufferView = void 0;
          this._normalizeFactor = 1;
          if (args.length === 2) {
            this._bufferView = args[0];
            this._normalizeFactor = args[1];
          } else {
            const arrayBuffer = args[0];
            const Ctor = args[1];
            const normalizeFactor = args[2];
            this._bufferView = new Ctor(arrayBuffer);
            this._normalizeFactor = normalizeFactor;
          }
        }
        get length() {
          return this._bufferView.length;
        }
        getData(offset) {
          return this._bufferView[offset] * this._normalizeFactor;
        }
      } exports("AudioPCMDataView", AudioPCMDataView);

      function removeUnneededCalls(instance) {
        const size = instance._operationQueue.length;
        const tmpQueue = instance._operationQueue.slice();
        const reserveOps = [];
        let seekSearched = false;
        for (let i = size - 1; i >= 0; i--) {
          const 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();
      }
      let operationId = 0;
      function _tryCallingRecursively(target, opInfo) {
        if (opInfo.invoking) {
          return;
        }
        opInfo.invoking = true;
        opInfo.func.call(target, ...opInfo.args).then(() => {
          opInfo.invoking = false;
          target._operationQueue.shift();
          target._eventTarget.emit(opInfo.id.toString());
          removeUnneededCalls(target);
          const nextOpInfo = target._operationQueue[0];
          if (nextOpInfo) {
            _tryCallingRecursively(target, nextOpInfo);
          }
        }).catch(e => {});
      }
      function enqueueOperation(target, propertyKey, descriptor) {
        const originalOperation = descriptor.value;
        descriptor.value = function (...args) {
          return new Promise(resolve => {
            const id = operationId++;
            const instance = this;
            instance._operationQueue.push({
              op: propertyKey,
              id,
              func: originalOperation,
              args,
              invoking: false
            });
            instance._eventTarget.once(id.toString(), resolve);
            const opInfo = instance._operationQueue[0];
            _tryCallingRecursively(instance, opInfo);
          });
        };
      }

      var _class2$S, _class3$l;
      const urlCount = {};
      const audioEngine = jsb.AudioEngine;
      const INVALID_AUDIO_ID = -1;
      var AudioBufferFormat;
      (function (AudioBufferFormat) {
        AudioBufferFormat[AudioBufferFormat["UNKNOWN"] = 0] = "UNKNOWN";
        AudioBufferFormat[AudioBufferFormat["SIGNED_8"] = 1] = "SIGNED_8";
        AudioBufferFormat[AudioBufferFormat["UNSIGNED_8"] = 2] = "UNSIGNED_8";
        AudioBufferFormat[AudioBufferFormat["SIGNED_16"] = 3] = "SIGNED_16";
        AudioBufferFormat[AudioBufferFormat["UNSIGNED_16"] = 4] = "UNSIGNED_16";
        AudioBufferFormat[AudioBufferFormat["SIGNED_32"] = 5] = "SIGNED_32";
        AudioBufferFormat[AudioBufferFormat["UNSIGNED_32"] = 6] = "UNSIGNED_32";
        AudioBufferFormat[AudioBufferFormat["FLOAT_32"] = 7] = "FLOAT_32";
        AudioBufferFormat[AudioBufferFormat["FLOAT_64"] = 8] = "FLOAT_64";
      })(AudioBufferFormat || (AudioBufferFormat = {}));
      const bufferConstructorMap = {
        [AudioBufferFormat.UNKNOWN]: undefined,
        [AudioBufferFormat.SIGNED_8]: {
          ctor: Int8Array,
          maxValue: 127
        },
        [AudioBufferFormat.UNSIGNED_8]: {
          ctor: Uint8Array,
          maxValue: 255
        },
        [AudioBufferFormat.SIGNED_16]: {
          ctor: Int16Array,
          maxValue: 32767
        },
        [AudioBufferFormat.UNSIGNED_16]: {
          ctor: Uint16Array,
          maxValue: 65535
        },
        [AudioBufferFormat.SIGNED_32]: {
          ctor: Int32Array,
          maxValue: 2147483647
        },
        [AudioBufferFormat.UNSIGNED_32]: {
          ctor: Uint32Array,
          maxValue: 4294967295
        },
        [AudioBufferFormat.FLOAT_32]: {
          ctor: Float32Array,
          maxValue: 1
        },
        [AudioBufferFormat.FLOAT_64]: {
          ctor: Float64Array,
          maxValue: 1
        }
      };
      class OneShotAudio {
        get onPlay() {
          return this._onPlayCb;
        }
        set onPlay(cb) {
          this._onPlayCb = cb;
        }
        get onEnd() {
          return this._onEndCb;
        }
        set onEnd(cb) {
          this._onEndCb = cb;
        }
        constructor(url, volume) {
          this._id = INVALID_AUDIO_ID;
          this._url = void 0;
          this._volume = void 0;
          this._onPlayCb = void 0;
          this._onEndCb = void 0;
          this._url = url;
          this._volume = volume;
        }
        play() {
          var _this$onPlay;
          this._id = jsb.AudioEngine.play2d(this._url, false, this._volume);
          jsb.AudioEngine.setFinishCallback(this._id, () => {
            var _this$onEnd;
            (_this$onEnd = this.onEnd) === null || _this$onEnd === void 0 ? void 0 : _this$onEnd.call(this);
          });
          (_this$onPlay = this.onPlay) === null || _this$onPlay === void 0 ? void 0 : _this$onPlay.call(this);
        }
        stop() {
          if (this._id === INVALID_AUDIO_ID) {
            return;
          }
          jsb.AudioEngine.stop(this._id);
        }
      }
      let AudioPlayer = (_class2$S = (_class3$l = class AudioPlayer {
        constructor(url) {
          this._url = void 0;
          this._id = INVALID_AUDIO_ID;
          this._state = AudioState.INIT;
          this._pcmHeader = void 0;
          this._eventTarget = new EventTarget();
          this._operationQueue = [];
          this._cachedState = {
            duration: 1,
            loop: false,
            currentTime: 0,
            volume: 1
          };
          this._url = url;
          this._pcmHeader = null;
          game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
        }
        destroy() {
          game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          if (--urlCount[this._url] <= 0) {
            audioEngine.uncache(this._url);
          }
        }
        _onInterruptedBegin() {
          if (this._state === AudioState.PLAYING) {
            this.pause().then(() => {
              this._state = AudioState.INTERRUPTED;
              this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
            }).catch(e => {});
          }
        }
        _onInterruptedEnd() {
          if (this._state === AudioState.INTERRUPTED) {
            this.play().then(() => {
              this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
            }).catch(e => {});
          }
        }
        static load(url, opts) {
          return new Promise((resolve, reject) => {
            AudioPlayer.loadNative(url, opts).then(url => {
              resolve(new AudioPlayer(url));
            }).catch(err => reject(err));
          });
        }
        static loadNative(url, opts) {
          return new Promise((resolve, reject) => {
            if (systemInfo.platform === Platform.WIN32) {
              audioEngine.preload(url, isSuccess => {
                console.debug('somehow preload success on windows');
              });
              resolve(url);
            } else {
              audioEngine.preload(url, isSuccess => {
                if (isSuccess) {
                  resolve(url);
                } else {
                  reject(new Error('load audio failed'));
                }
              });
            }
          });
        }
        static loadOneShotAudio(url, volume, opts) {
          return new Promise((resolve, reject) => {
            AudioPlayer.loadNative(url, opts).then(url => {
              resolve(new OneShotAudio(url, volume));
            }).catch(reject);
          });
        }
        get _isValid() {
          return this._id !== INVALID_AUDIO_ID;
        }
        get src() {
          return this._url;
        }
        get type() {
          return AudioType.NATIVE_AUDIO;
        }
        get state() {
          return this._state;
        }
        get loop() {
          if (!this._isValid) {
            return this._cachedState.loop;
          }
          return audioEngine.isLoop(this._id);
        }
        set loop(val) {
          if (this._isValid) {
            audioEngine.setLoop(this._id, val);
          }
          this._cachedState.loop = val;
        }
        get volume() {
          if (!this._isValid) {
            return this._cachedState.volume;
          }
          return audioEngine.getVolume(this._id);
        }
        set volume(val) {
          val = clamp01(val);
          if (this._isValid) {
            audioEngine.setVolume(this._id, val);
          }
          this._cachedState.volume = val;
        }
        get duration() {
          if (!this._isValid) {
            return this._cachedState.duration;
          }
          return audioEngine.getDuration(this._id);
        }
        get currentTime() {
          if (!this._isValid) {
            return this._cachedState.currentTime;
          }
          return audioEngine.getCurrentTime(this._id);
        }
        get sampleRate() {
          if (this._pcmHeader === null) {
            this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url);
          }
          return this._pcmHeader.sampleRate;
        }
        getPCMData(channelIndex) {
          const arrayBuffer = audioEngine.getOriginalPCMBuffer(this._url, channelIndex);
          if (this._pcmHeader === null) {
            this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url);
          }
          const audioBufferInfo = bufferConstructorMap[this._pcmHeader.audioFormat];
          if (!arrayBuffer || !audioBufferInfo) {
            return undefined;
          }
          return new AudioPCMDataView(arrayBuffer, audioBufferInfo.ctor, 1 / audioBufferInfo.maxValue);
        }
        seek(time) {
          return new Promise(resolve => {
            if (this._isValid) {
              audioEngine.setCurrentTime(this._id, time);
            }
            this._cachedState.currentTime = time;
            return resolve();
          });
        }
        play() {
          return new Promise(resolve => {
            if (this._isValid) {
              if (this._state === AudioState.PAUSED || this._state === AudioState.INTERRUPTED) {
                audioEngine.resume(this._id);
              } else if (this._state === AudioState.PLAYING) {
                audioEngine.pause(this._id);
                audioEngine.setCurrentTime(this._id, 0);
                audioEngine.resume(this._id);
              }
            } else {
              this._id = audioEngine.play2d(this._url, this._cachedState.loop, this._cachedState.volume);
              if (this._isValid) {
                if (this._cachedState.currentTime !== 0) {
                  audioEngine.setCurrentTime(this._id, this._cachedState.currentTime);
                  this._cachedState.currentTime = 0;
                }
                audioEngine.setFinishCallback(this._id, () => {
                  this._cachedState.currentTime = 0;
                  this._id = INVALID_AUDIO_ID;
                  this._state = AudioState.INIT;
                  this._eventTarget.emit(AudioEvent.ENDED);
                });
              }
            }
            this._state = AudioState.PLAYING;
            resolve();
          });
        }
        pause() {
          return new Promise(resolve => {
            if (this._isValid) {
              audioEngine.pause(this._id);
            }
            this._state = AudioState.PAUSED;
            resolve();
          });
        }
        stop() {
          return new Promise(resolve => {
            if (this._isValid) {
              audioEngine.stop(this._id);
            }
            this._state = AudioState.STOPPED;
            this._id = INVALID_AUDIO_ID;
            this._cachedState.currentTime = 0;
            resolve();
          });
        }
        onInterruptionBegin(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
        }
        offInterruptionBegin(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
        }
        onInterruptionEnd(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
        }
        offInterruptionEnd(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
        }
        onEnded(cb) {
          this._eventTarget.on(AudioEvent.ENDED, cb);
        }
        offEnded(cb) {
          this._eventTarget.off(AudioEvent.ENDED, cb);
        }
      }, _class3$l.maxAudioChannel = audioEngine.getMaxAudioInstance(), _class3$l), (_applyDecoratedDescriptor(_class2$S.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$S.prototype, "seek"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$S.prototype, "play"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$S.prototype, "pause"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$S.prototype, "stop"), _class2$S.prototype)), _class2$S);
      legacyCC.AudioPlayer = AudioPlayer;

      var _dec$Z, _class$Y, _class2$R, _initializer$O, _class3$k;
      let AudioClip = exports("AudioClip", (_dec$Z = ccclass$H('cc.AudioClip'), _dec$Z(_class$Y = (_class2$R = (_class3$k = class AudioClip extends Asset {
        set duration(v) {
          this._duration = v;
        }
        constructor() {
          super();
          this._duration = _initializer$O && _initializer$O();
          this._loadMode = AudioType.UNKNOWN_AUDIO;
          this._meta = null;
          this._player = null;
        }
        destroy() {
          var _this$_player;
          const destroyResult = super.destroy();
          (_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;
        }
        set _nativeAsset(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;
          }
        }
        get _nativeAsset() {
          return this._meta;
        }
        get _nativeDep() {
          return {
            uuid: this._uuid,
            audioLoadMode: this.loadMode,
            ext: this._native,
            __isNative__: true
          };
        }
        get loadMode() {
          return this._loadMode;
        }
        validate() {
          return !!this._meta;
        }
        getDuration() {
          if (this._duration) {
            return this._duration;
          }
          return this._meta ? this._meta.duration : 0;
        }
        get state() {
          return this._player ? this._player.state : AudioState.INIT;
        }
        getCurrentTime() {
          return this._player ? this._player.currentTime : 0;
        }
        getVolume() {
          return this._player ? this._player.volume : 0;
        }
        getLoop() {
          return this._player ? this._player.loop : false;
        }
        setCurrentTime(time) {
          var _this$_player2;
          (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.seek(time).catch(e => {});
        }
        setVolume(volume) {
          if (this._player) {
            this._player.volume = volume;
          }
        }
        setLoop(loop) {
          if (this._player) {
            this._player.loop = loop;
          }
        }
        play() {
          var _this$_player3;
          (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.play().catch(e => {});
        }
        pause() {
          var _this$_player4;
          (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.pause().catch(e => {});
        }
        stop() {
          var _this$_player5;
          (_this$_player5 = this._player) === null || _this$_player5 === void 0 ? void 0 : _this$_player5.stop().catch(e => {});
        }
        playOneShot(volume = 1) {
          if (this._nativeAsset) {
            AudioPlayer.loadOneShotAudio(this._nativeAsset.url, volume).then(oneShotAudio => {
              oneShotAudio.play();
            }).catch(e => {});
          }
        }
      }, _class3$k.AudioType = AudioType, _class3$k), (_initializer$O = applyDecoratedInitializer(_class2$R.prototype, "_duration", [serializable$l], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$R.prototype, "_nativeDep", [override$1], Object.getOwnPropertyDescriptor(_class2$R.prototype, "_nativeDep"), _class2$R.prototype)), _class2$R)) || _class$Y));
      cclegacy.AudioClip = AudioClip;

      function loadAudioPlayer(url, options, onComplete) {
        AudioPlayer.load(url, {
          audioLoadMode: options.audioLoadMode
        }).then(player => {
          const audioMeta = {
            player,
            url,
            duration: player.duration,
            type: player.type
          };
          onComplete(null, audioMeta);
        }).catch(err => {
          onComplete(err);
        });
      }
      function createAudioClip(id, data, options, onComplete) {
        const 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
      });

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

      var _dec$Y, _dec2$O, _dec3$G, _class$X, _class2$Q, _initializer$N, _initializer2$H, _initializer3$z, _initializer4$w, _class3$j;
      const _LOADED_EVENT = 'audiosource-loaded';
      const AudioSourceEventType = {
        "STARTED": "started",
        "ENDED": "ended"
      };
      let AudioSource = (_dec$Y = ccclass$H('cc.AudioSource'), _dec2$O = type$a(AudioClip), _dec3$G = type$a(AudioClip), _dec$Y(_class$X = (_class2$Q = (_class3$j = class AudioSource extends Component {
        static get maxAudioChannel() {
          return AudioPlayer.maxAudioChannel;
        }
        constructor() {
          super();
          this._clip = _initializer$N && _initializer$N();
          this._player = null;
          this._hasRegisterListener = false;
          this._loop = _initializer2$H && _initializer2$H();
          this._playOnAwake = _initializer3$z && _initializer3$z();
          this._volume = _initializer4$w && _initializer4$w();
          this._cachedCurrentTime = -1;
          this._operationsBeforeLoading = [];
          this._isLoaded = false;
          this._lastSetClip = null;
        }
        _resetPlayer() {
          if (this._player) {
            audioManager.removePlaying(this._player);
            this._unregisterListener();
            this._player.destroy();
            this._player = null;
          }
        }
        set clip(val) {
          if (val === this._clip) {
            return;
          }
          this._clip = val;
          this._syncPlayer();
        }
        get clip() {
          return this._clip;
        }
        _syncPlayer() {
          const 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(player => {
            var _this$node;
            if (this._lastSetClip !== clip) {
              player.destroy();
              return;
            }
            this._isLoaded = true;
            this._resetPlayer();
            this._player = player;
            this._syncStates();
            (_this$node = this.node) === null || _this$node === void 0 ? void 0 : _this$node.emit(_LOADED_EVENT);
          }).catch(e => {});
        }
        _registerListener() {
          if (!this._hasRegisterListener && this._player) {
            const player = this._player;
            player.onEnded(() => {
              var _this$node2;
              audioManager.removePlaying(player);
              (_this$node2 = this.node) === null || _this$node2 === void 0 ? void 0 : _this$node2.emit("ended", this);
            });
            player.onInterruptionBegin(() => {
              audioManager.removePlaying(player);
            });
            player.onInterruptionEnd(() => {
              if (this._player === player) {
                audioManager.addPlaying(player);
              }
            });
            this._hasRegisterListener = true;
          }
        }
        _unregisterListener() {
          if (this._player && this._hasRegisterListener) {
            this._player.offEnded();
            this._player.offInterruptionBegin();
            this._player.offInterruptionEnd();
            this._hasRegisterListener = false;
          }
        }
        set loop(val) {
          this._loop = val;
          if (this._player) {
            this._player.loop = val;
          }
        }
        get loop() {
          return this._loop;
        }
        set playOnAwake(val) {
          this._playOnAwake = val;
        }
        get playOnAwake() {
          return this._playOnAwake;
        }
        set volume(val) {
          if (Number.isNaN(val)) {
            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;
          }
        }
        get volume() {
          return this._volume;
        }
        onLoad() {
          this._syncPlayer();
        }
        onEnable() {
          if (this._playOnAwake && !this.playing) {
            this.play();
          }
        }
        onDisable() {
          const rootNode = this._getRootNode();
          if (rootNode !== null && rootNode !== void 0 && rootNode._persistNode) {
            return;
          }
          this.pause();
        }
        onDestroy() {
          this.stop();
          this.clip = null;
        }
        getPCMData(channelIndex) {
          return new Promise(resolve => {
            if (channelIndex !== 0 && channelIndex !== 1) {
              warn('Only support channel index 0 or 1 to get buffer');
              resolve(undefined);
              return;
            }
            if (this._player) {
              resolve(this._player.getPCMData(channelIndex));
            } else {
              var _this$node3;
              (_this$node3 = this.node) === null || _this$node3 === void 0 ? void 0 : _this$node3.once(_LOADED_EVENT, () => {
                var _this$_player;
                resolve((_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.getPCMData(channelIndex));
              });
            }
          });
        }
        getSampleRate() {
          return new Promise(resolve => {
            if (this._player) {
              resolve(this._player.sampleRate);
            } else {
              var _this$node4;
              (_this$node4 = this.node) === null || _this$node4 === void 0 ? void 0 : _this$node4.once(_LOADED_EVENT, () => {
                resolve(this._player.sampleRate);
              });
            }
          });
        }
        _getRootNode() {
          var _currentNode, _currentNode$parent;
          let currentNode = this.node;
          let 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;
        }
        play() {
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: "play",
              params: null
            });
            return;
          }
          this._registerListener();
          audioManager.discardOnePlayingIfNeeded();
          if (this.state === AudioState.PLAYING) {
            var _this$_player2;
            (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.stop().catch(e => {});
          }
          const player = this._player;
          if (player) {
            player.play().then(() => {
              var _this$node5;
              (_this$node5 = this.node) === null || _this$node5 === void 0 ? void 0 : _this$node5.emit("started", this);
            }).catch(e => {
              audioManager.removePlaying(player);
            });
            audioManager.addPlaying(player);
          }
        }
        pause() {
          var _this$_player3;
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: "pause",
              params: null
            });
            return;
          }
          (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.pause().catch(e => {});
        }
        stop() {
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: "stop",
              params: null
            });
            return;
          }
          if (this._player) {
            this._player.stop().catch(e => {});
            audioManager.removePlaying(this._player);
          }
        }
        playOneShot(clip, volumeScale = 1) {
          if (!clip._nativeAsset) {
            console.error('Invalid audio clip');
            return;
          }
          let player;
          AudioPlayer.loadOneShotAudio(clip._nativeAsset.url, this._volume * volumeScale, {
            audioLoadMode: clip.loadMode
          }).then(oneShotAudio => {
            player = oneShotAudio;
            audioManager.discardOnePlayingIfNeeded();
            oneShotAudio.onEnd = () => {
              audioManager.removePlaying(oneShotAudio);
            };
            oneShotAudio.play();
            audioManager.addPlaying(oneShotAudio);
          }).catch(e => {
            if (player) {
              audioManager.removePlaying(player);
            }
          });
        }
        _syncStates() {
          if (this._player) {
            this._player.loop = this._loop;
            this._player.volume = this._volume;
            this._operationsBeforeLoading.forEach(opInfo => {
              if (opInfo.op === "seek") {
                this._cachedCurrentTime = opInfo.params && opInfo.params[0];
                if (this._player) {
                  this._player.seek(this._cachedCurrentTime).catch(e => {});
                }
              } else {
                var _this$opInfo$op;
                (_this$opInfo$op = this[opInfo.op]) === null || _this$opInfo$op === void 0 ? void 0 : _this$opInfo$op.call(this);
              }
            });
            this._operationsBeforeLoading.length = 0;
          }
        }
        set currentTime(num) {
          var _this$_player4;
          if (Number.isNaN(num)) {
            warn('illegal audio time!');
            return;
          }
          num = clamp$1(num, 0, this.duration);
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: "seek",
              params: [num]
            });
            return;
          }
          this._cachedCurrentTime = num;
          (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.seek(this._cachedCurrentTime).catch(e => {});
        }
        get currentTime() {
          return this._player ? this._player.currentTime : this._cachedCurrentTime < 0 ? 0 : this._cachedCurrentTime;
        }
        get duration() {
          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;
        }
        get state() {
          return this._player ? this._player.state : AudioState.INIT;
        }
        get playing() {
          return this.state === AudioSource.AudioState.PLAYING;
        }
      }, _class3$j.AudioState = AudioState, _class3$j.EventType = AudioSourceEventType, _class3$j), (_initializer$N = applyDecoratedInitializer(_class2$Q.prototype, "_clip", [_dec2$O], function () {
        return null;
      }), _initializer2$H = applyDecoratedInitializer(_class2$Q.prototype, "_loop", [serializable$l], function () {
        return false;
      }), _initializer3$z = applyDecoratedInitializer(_class2$Q.prototype, "_playOnAwake", [serializable$l], function () {
        return true;
      }), _initializer4$w = applyDecoratedInitializer(_class2$Q.prototype, "_volume", [serializable$l], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$Q.prototype, "clip", [_dec3$G], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "clip"), _class2$Q.prototype)), _class2$Q)) || _class$X); exports({ AudioSource: AudioSource, AudioSourceComponent: AudioSource });

      replaceProperty(AudioClip, 'AudioClip', [{
        name: 'PlayingState',
        newName: 'AudioState',
        target: AudioSource,
        targetName: 'AudioSource'
      }]);
      markAsWarning(AudioClip.prototype, 'AudioClip.prototype', ['state', 'play', 'pause', 'stop', 'playOneShot', 'setCurrentTime', 'setVolume', 'setLoop', 'getCurrentTime', 'getVolume', 'getLoop'].map(item => ({
        name: item,
        suggest: `please use AudioSource.prototype.${item} instead`
      })));

      cclegacy.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,
        extname,
        mainFileName,
        basename,
        dirname,
        changeExtname,
        changeBasename,
        _normalize,
        stripSep,
        get sep() {
          return getSeperator();
        }
      };

      class NodePool {
        constructor(poolHandlerComp) {
          this._pool = [];
          this.poolHandlerComp = poolHandlerComp;
        }
        size() {
          return this._pool.length;
        }
        clear() {
          const count = this._pool.length;
          for (let i = 0; i < count; ++i) {
            this._pool[i].destroy();
          }
          this._pool.length = 0;
        }
        put(obj) {
          if (obj && this._pool.indexOf(obj) === -1) {
            obj.removeFromParent();
            const handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.unuse) {
              handler.unuse();
            }
            this._pool.push(obj);
          }
        }
        get(...args) {
          const last = this._pool.length - 1;
          if (last < 0) {
            return null;
          } else {
            const obj = this._pool[last];
            this._pool.length = last;
            const handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.reuse) {
              handler.reuse(arguments);
            }
            return obj;
          }
        }
      } exports("NodePool", NodePool);
      legacyCC.NodePool = NodePool;

      var _globalThis$jsb, _globalJsb$copyTextTo;
      const globalJsb = (_globalThis$jsb = globalThis.jsb) !== null && _globalThis$jsb !== void 0 ? _globalThis$jsb : {};
      {
        Object.defineProperty(globalJsb, 'reflection', {
          get() {
            if (globalJsb.__bridge !== undefined) return globalJsb.__bridge;
            if (globalThis.JavascriptJavaBridge && (sys.os === sys.OS.ANDROID || sys.os === sys.OS.OHOS)) {
              globalJsb.__bridge = new globalThis.JavascriptJavaBridge();
            } else if (globalThis.JavaScriptObjCBridge && (sys.os === sys.OS.IOS || sys.os === sys.OS.OSX)) {
              globalJsb.__bridge = new globalThis.JavaScriptObjCBridge();
            } else if (globalThis.JavaScriptArkTsBridge && sys.os === sys.OS.OPENHARMONY) {
              globalJsb.__bridge = new globalThis.JavaScriptArkTsBridge();
            } else {
              globalJsb.__bridge = null;
            }
            return globalJsb.__bridge;
          },
          enumerable: true,
          configurable: true,
          set(value) {
            globalJsb.__bridge = value;
          }
        });
        Object.defineProperty(globalJsb, 'bridge', {
          get() {
            if (globalJsb.__ccbridge !== undefined) return globalJsb.__ccbridge;
            if (globalThis.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) {
              globalJsb.__ccbridge = new ScriptNativeBridge();
            } else {
              globalJsb.__ccbridge = null;
            }
            return globalJsb.__ccbridge;
          },
          enumerable: true,
          configurable: true,
          set(value) {
            globalJsb.__ccbridge = value;
          }
        });
        const JsbBridgeWrapper = {
          eventMap: new Map(),
          addNativeEventListener(eventName, listener) {
            if (!this.eventMap.get(eventName)) {
              this.eventMap.set(eventName, []);
            }
            const arr = this.eventMap.get(eventName);
            if (!arr.includes(listener)) {
              arr.push(listener);
            }
          },
          dispatchEventToNative(eventName, arg) {
            globalJsb.bridge.sendToNative(eventName, arg);
          },
          removeAllListenersForEvent(eventName) {
            return this.eventMap.delete(eventName);
          },
          removeNativeEventListener(eventName, listener) {
            const arr = this.eventMap.get(eventName);
            if (!arr) {
              return false;
            }
            for (let i = 0, l = arr.length; i < l; i++) {
              if (arr[i] === listener) {
                arr.splice(i, 1);
                return true;
              }
            }
            return true;
          },
          removeAllListeners() {
            this.eventMap.clear();
          },
          triggerEvent(eventName, arg) {
            const arr = this.eventMap.get(eventName);
            if (!arr) {
              console.error(`${eventName} does not exist`);
              return;
            }
            arr.map(listener => listener.call(null, arg));
          }
        };
        Object.defineProperty(globalJsb, 'jsbBridgeWrapper', {
          get() {
            if (globalJsb.__JsbBridgeWrapper !== undefined) return globalJsb.__JsbBridgeWrapper;
            if (globalThis.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) {
              globalJsb.__JsbBridgeWrapper = JsbBridgeWrapper;
              globalJsb.bridge.onNative = (methodName, arg1) => {
                globalJsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1);
              };
            } else {
              globalJsb.__JsbBridgeWrapper = null;
            }
            return globalJsb.__JsbBridgeWrapper;
          },
          enumerable: true,
          configurable: true,
          set(value) {
            globalJsb.__JsbBridgeWrapper = value;
          }
        });
        const originSaveImageData = globalJsb.saveImageData;
        globalJsb.saveImageData = (data, width, height, filePath) => {
          return new Promise((resolve, reject) => {
            originSaveImageData(data, width, height, filePath, isSuccess => {
              if (isSuccess) {
                resolve();
              } else {
                reject();
              }
            });
          });
        };
      }
      const native = exports("native", {
        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,
        adpf: globalJsb.adpf
      });

      legacyCC.renderer = renderer;

      var __extends=undefined&&undefined.__extends||function(){var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];};return function(d,b){extendStatics(d,b);function __(){this.constructor=d;}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());};}();let dragonBones$1={};(function(dragonBones){})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var DragonBones=function(){function DragonBones(eventManager){this._clock=new dragonBones.WorldClock();this._events=[];this._objects=[];this._eventManager=null;this._eventManager=eventManager;console.info("DragonBones: "+DragonBones.VERSION+"\nWebsite: http://dragonbones.com/\nSource and Demo: https://github.com/DragonBones/");}DragonBones.prototype.advanceTime=function(passedTime){if(this._objects.length>0){for(var _i=0,_a=this._objects;_i<_a.length;_i++){var object=_a[_i];object.returnToPool();}this._objects.length=0;}this._clock.advanceTime(passedTime);if(this._events.length>0){for(var i=0;i<this._events.length;++i){var eventObject=this._events[i];var armature=eventObject.armature;if(armature._armatureData!==null){armature.eventDispatcher.dispatchDBEvent(eventObject.type,eventObject);if(eventObject.type===dragonBones.EventObject.SOUND_EVENT){this._eventManager.dispatchDBEvent(eventObject.type,eventObject);}}this.bufferObject(eventObject);}this._events.length=0;}};DragonBones.prototype.bufferEvent=function(value){if(this._events.indexOf(value)<0){this._events.push(value);}};DragonBones.prototype.bufferObject=function(object){if(this._objects.indexOf(object)<0){this._objects.push(object);}};Object.defineProperty(DragonBones.prototype,"clock",{get:function(){return this._clock;},enumerable:true,configurable:true});Object.defineProperty(DragonBones.prototype,"eventManager",{get:function(){return this._eventManager;},enumerable:true,configurable:true});DragonBones.VERSION="5.6.300";DragonBones.yDown=false;DragonBones.debug=false;DragonBones.debugDraw=false;DragonBones.webAssembly=false;return DragonBones;}();dragonBones.DragonBones=DragonBones;})(dragonBones$1||(dragonBones$1={}));if(!console.warn){console.warn=function(){};}if(!console.assert){console.assert=function(){};}if(!Date.now){Date.now=function now(){return new Date().getTime();};}var __extends=function(t,e){function r(){this.constructor=t;}for(var i in e){if(e.hasOwnProperty(i)){t[i]=e[i];}}r.prototype=e.prototype,t.prototype=new r();};(function(dragonBones){var BaseObject=function(){function BaseObject(){this.hashCode=BaseObject._hashCode++;this._isInPool=false;}BaseObject._returnObject=function(object){var classType=String(object.constructor);var maxCount=classType in BaseObject._maxCountMap?BaseObject._maxCountMap[classType]:BaseObject._defaultMaxCount;var pool=BaseObject._poolsMap[classType]=BaseObject._poolsMap[classType]||[];if(pool.length<maxCount){if(!object._isInPool){object._isInPool=true;pool.push(object);}else {console.warn("The object is already in the pool.");}}};BaseObject.toString=function(){throw new Error();};BaseObject.setMaxCount=function(objectConstructor,maxCount){if(maxCount<0||maxCount!==maxCount){maxCount=0;}if(objectConstructor!==null){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>maxCount){pool.length=maxCount;}BaseObject._maxCountMap[classType]=maxCount;}else {BaseObject._defaultMaxCount=maxCount;for(var classType in BaseObject._poolsMap){var pool=BaseObject._poolsMap[classType];if(pool.length>maxCount){pool.length=maxCount;}if(classType in BaseObject._maxCountMap){BaseObject._maxCountMap[classType]=maxCount;}}}};BaseObject.clearPool=function(objectConstructor){if(objectConstructor===void 0){objectConstructor=null;}if(objectConstructor!==null){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>0){pool.length=0;}}else {for(var k in BaseObject._poolsMap){var pool=BaseObject._poolsMap[k];pool.length=0;}}};BaseObject.borrowObject=function(objectConstructor){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>0){var object_1=pool.pop();object_1._isInPool=false;return object_1;}var object=new objectConstructor();object._onClear();return object;};BaseObject.prototype.returnToPool=function(){this._onClear();BaseObject._returnObject(this);};BaseObject._hashCode=0;BaseObject._defaultMaxCount=3000;BaseObject._maxCountMap={};BaseObject._poolsMap={};return BaseObject;}();dragonBones.BaseObject=BaseObject;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Matrix=function(){function Matrix(a,b,c,d,tx,ty){if(a===void 0){a=1.0;}if(b===void 0){b=0.0;}if(c===void 0){c=0.0;}if(d===void 0){d=1.0;}if(tx===void 0){tx=0.0;}if(ty===void 0){ty=0.0;}this.a=a;this.b=b;this.c=c;this.d=d;this.tx=tx;this.ty=ty;}Matrix.prototype.toString=function(){return "[object dragonBones.Matrix] a:"+this.a+" b:"+this.b+" c:"+this.c+" d:"+this.d+" tx:"+this.tx+" ty:"+this.ty;};Matrix.prototype.copyFrom=function(value){this.a=value.a;this.b=value.b;this.c=value.c;this.d=value.d;this.tx=value.tx;this.ty=value.ty;return this;};Matrix.prototype.copyFromArray=function(value,offset){if(offset===void 0){offset=0;}this.a=value[offset];this.b=value[offset+1];this.c=value[offset+2];this.d=value[offset+3];this.tx=value[offset+4];this.ty=value[offset+5];return this;};Matrix.prototype.identity=function(){this.a=this.d=1.0;this.b=this.c=0.0;this.tx=this.ty=0.0;return this;};Matrix.prototype.concat=function(value){var aA=this.a*value.a;var bA=0.0;var cA=0.0;var dA=this.d*value.d;var txA=this.tx*value.a+value.tx;var tyA=this.ty*value.d+value.ty;if(this.b!==0.0||this.c!==0.0){aA+=this.b*value.c;bA+=this.b*value.d;cA+=this.c*value.a;dA+=this.c*value.b;}if(value.b!==0.0||value.c!==0.0){bA+=this.a*value.b;cA+=this.d*value.c;txA+=this.ty*value.c;tyA+=this.tx*value.b;}this.a=aA;this.b=bA;this.c=cA;this.d=dA;this.tx=txA;this.ty=tyA;return this;};Matrix.prototype.invert=function(){var aA=this.a;var bA=this.b;var cA=this.c;var dA=this.d;var txA=this.tx;var tyA=this.ty;if(bA===0.0&&cA===0.0){this.b=this.c=0.0;if(aA===0.0||dA===0.0){this.a=this.b=this.tx=this.ty=0.0;}else {aA=this.a=1.0/aA;dA=this.d=1.0/dA;this.tx=-aA*txA;this.ty=-dA*tyA;}return this;}var determinant=aA*dA-bA*cA;if(determinant===0.0){this.a=this.d=1.0;this.b=this.c=0.0;this.tx=this.ty=0.0;return this;}determinant=1.0/determinant;var k=this.a=dA*determinant;bA=this.b=-bA*determinant;cA=this.c=-cA*determinant;dA=this.d=aA*determinant;this.tx=-(k*txA+cA*tyA);this.ty=-(bA*txA+dA*tyA);return this;};Matrix.prototype.transformPoint=function(x,y,result,delta){if(delta===void 0){delta=false;}result.x=this.a*x+this.c*y;result.y=this.b*x+this.d*y;if(!delta){result.x+=this.tx;result.y+=this.ty;}};Matrix.prototype.transformRectangle=function(rectangle,delta){if(delta===void 0){delta=false;}var a=this.a;var b=this.b;var c=this.c;var d=this.d;var tx=delta?0.0:this.tx;var ty=delta?0.0:this.ty;var x=rectangle.x;var y=rectangle.y;var xMax=x+rectangle.width;var yMax=y+rectangle.height;var x0=a*x+c*y+tx;var y0=b*x+d*y+ty;var x1=a*xMax+c*y+tx;var y1=b*xMax+d*y+ty;var x2=a*xMax+c*yMax+tx;var y2=b*xMax+d*yMax+ty;var x3=a*x+c*yMax+tx;var y3=b*x+d*yMax+ty;var tmp=0.0;if(x0>x1){tmp=x0;x0=x1;x1=tmp;}if(x2>x3){tmp=x2;x2=x3;x3=tmp;}rectangle.x=Math.floor(x0<x2?x0:x2);rectangle.width=Math.ceil((x1>x3?x1:x3)-rectangle.x);if(y0>y1){tmp=y0;y0=y1;y1=tmp;}if(y2>y3){tmp=y2;y2=y3;y3=tmp;}rectangle.y=Math.floor(y0<y2?y0:y2);rectangle.height=Math.ceil((y1>y3?y1:y3)-rectangle.y);};return Matrix;}();dragonBones.Matrix=Matrix;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Transform=function(){function Transform(x,y,skew,rotation,scaleX,scaleY){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}if(skew===void 0){skew=0.0;}if(rotation===void 0){rotation=0.0;}if(scaleX===void 0){scaleX=1.0;}if(scaleY===void 0){scaleY=1.0;}this.x=x;this.y=y;this.skew=skew;this.rotation=rotation;this.scaleX=scaleX;this.scaleY=scaleY;}Transform.normalizeRadian=function(value){value=(value+Math.PI)%(Math.PI*2.0);value+=value>0.0?-Math.PI:Math.PI;return value;};Transform.prototype.toString=function(){return "[object dragonBones.Transform] x:"+this.x+" y:"+this.y+" skewX:"+this.skew*180.0/Math.PI+" skewY:"+this.rotation*180.0/Math.PI+" scaleX:"+this.scaleX+" scaleY:"+this.scaleY;};Transform.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;this.skew=value.skew;this.rotation=value.rotation;this.scaleX=value.scaleX;this.scaleY=value.scaleY;return this;};Transform.prototype.identity=function(){this.x=this.y=0.0;this.skew=this.rotation=0.0;this.scaleX=this.scaleY=1.0;return this;};Transform.prototype.add=function(value){this.x+=value.x;this.y+=value.y;this.skew+=value.skew;this.rotation+=value.rotation;this.scaleX*=value.scaleX;this.scaleY*=value.scaleY;return this;};Transform.prototype.minus=function(value){this.x-=value.x;this.y-=value.y;this.skew-=value.skew;this.rotation-=value.rotation;this.scaleX/=value.scaleX;this.scaleY/=value.scaleY;return this;};Transform.prototype.fromMatrix=function(matrix){var backupScaleX=this.scaleX,backupScaleY=this.scaleY;var PI_Q=Transform.PI_Q;this.x=matrix.tx;this.y=matrix.ty;this.rotation=Math.atan(matrix.b/matrix.a);var skewX=Math.atan(-matrix.c/matrix.d);this.scaleX=this.rotation>-PI_Q&&this.rotation<PI_Q?matrix.a/Math.cos(this.rotation):matrix.b/Math.sin(this.rotation);this.scaleY=skewX>-PI_Q&&skewX<PI_Q?matrix.d/Math.cos(skewX):-matrix.c/Math.sin(skewX);if(backupScaleX>=0.0&&this.scaleX<0.0){this.scaleX=-this.scaleX;this.rotation=this.rotation-Math.PI;}if(backupScaleY>=0.0&&this.scaleY<0.0){this.scaleY=-this.scaleY;skewX=skewX-Math.PI;}this.skew=skewX-this.rotation;return this;};Transform.prototype.toMatrix=function(matrix){if(this.rotation===0.0){matrix.a=1.0;matrix.b=0.0;}else {matrix.a=Math.cos(this.rotation);matrix.b=Math.sin(this.rotation);}if(this.skew===0.0){matrix.c=-matrix.b;matrix.d=matrix.a;}else {matrix.c=-Math.sin(this.skew+this.rotation);matrix.d=Math.cos(this.skew+this.rotation);}if(this.scaleX!==1.0){matrix.a*=this.scaleX;matrix.b*=this.scaleX;}if(this.scaleY!==1.0){matrix.c*=this.scaleY;matrix.d*=this.scaleY;}matrix.tx=this.x;matrix.ty=this.y;return this;};Transform.PI=Math.PI;Transform.PI_D=Math.PI*2.0;Transform.PI_H=Math.PI/2.0;Transform.PI_Q=Math.PI/4.0;Transform.RAD_DEG=180.0/Math.PI;Transform.DEG_RAD=Math.PI/180.0;return Transform;}();dragonBones.Transform=Transform;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var ColorTransform=function(){function ColorTransform(alphaMultiplier,redMultiplier,greenMultiplier,blueMultiplier,alphaOffset,redOffset,greenOffset,blueOffset){if(alphaMultiplier===void 0){alphaMultiplier=1.0;}if(redMultiplier===void 0){redMultiplier=1.0;}if(greenMultiplier===void 0){greenMultiplier=1.0;}if(blueMultiplier===void 0){blueMultiplier=1.0;}if(alphaOffset===void 0){alphaOffset=0;}if(redOffset===void 0){redOffset=0;}if(greenOffset===void 0){greenOffset=0;}if(blueOffset===void 0){blueOffset=0;}this.alphaMultiplier=alphaMultiplier;this.redMultiplier=redMultiplier;this.greenMultiplier=greenMultiplier;this.blueMultiplier=blueMultiplier;this.alphaOffset=alphaOffset;this.redOffset=redOffset;this.greenOffset=greenOffset;this.blueOffset=blueOffset;}ColorTransform.prototype.copyFrom=function(value){this.alphaMultiplier=value.alphaMultiplier;this.redMultiplier=value.redMultiplier;this.greenMultiplier=value.greenMultiplier;this.blueMultiplier=value.blueMultiplier;this.alphaOffset=value.alphaOffset;this.redOffset=value.redOffset;this.greenOffset=value.greenOffset;this.blueOffset=value.blueOffset;};ColorTransform.prototype.identity=function(){this.alphaMultiplier=this.redMultiplier=this.greenMultiplier=this.blueMultiplier=1.0;this.alphaOffset=this.redOffset=this.greenOffset=this.blueOffset=0;};return ColorTransform;}();dragonBones.ColorTransform=ColorTransform;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Point=function(){function Point(x,y){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}this.x=x;this.y=y;}Point.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;};Point.prototype.clear=function(){this.x=this.y=0.0;};return Point;}();dragonBones.Point=Point;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Rectangle=function(){function Rectangle(x,y,width,height){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}if(width===void 0){width=0.0;}if(height===void 0){height=0.0;}this.x=x;this.y=y;this.width=width;this.height=height;}Rectangle.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;this.width=value.width;this.height=value.height;};Rectangle.prototype.clear=function(){this.x=this.y=0.0;this.width=this.height=0.0;};return Rectangle;}();dragonBones.Rectangle=Rectangle;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var UserData=function(_super){__extends(UserData,_super);function UserData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.ints=[];_this.floats=[];_this.strings=[];return _this;}UserData.toString=function(){return "[class dragonBones.UserData]";};UserData.prototype._onClear=function(){this.ints.length=0;this.floats.length=0;this.strings.length=0;};UserData.prototype.addInt=function(value){this.ints.push(value);};UserData.prototype.addFloat=function(value){this.floats.push(value);};UserData.prototype.addString=function(value){this.strings.push(value);};UserData.prototype.getInt=function(index){if(index===void 0){index=0;}return index>=0&&index<this.ints.length?this.ints[index]:0;};UserData.prototype.getFloat=function(index){if(index===void 0){index=0;}return index>=0&&index<this.floats.length?this.floats[index]:0.0;};UserData.prototype.getString=function(index){if(index===void 0){index=0;}return index>=0&&index<this.strings.length?this.strings[index]:"";};return UserData;}(dragonBones.BaseObject);dragonBones.UserData=UserData;var ActionData=function(_super){__extends(ActionData,_super);function ActionData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.data=null;return _this;}ActionData.toString=function(){return "[class dragonBones.ActionData]";};ActionData.prototype._onClear=function(){if(this.data!==null){this.data.returnToPool();}this.type=0;this.name="";this.bone=null;this.slot=null;this.data=null;};return ActionData;}(dragonBones.BaseObject);dragonBones.ActionData=ActionData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var DragonBonesData=function(_super){__extends(DragonBonesData,_super);function DragonBonesData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.frameIndices=[];_this.cachedFrames=[];_this.armatureNames=[];_this.armatures={};_this.userData=null;return _this;}DragonBonesData.toString=function(){return "[class dragonBones.DragonBonesData]";};DragonBonesData.prototype._onClear=function(){for(var k in this.armatures){this.armatures[k].returnToPool();delete this.armatures[k];}if(this.userData!==null){this.userData.returnToPool();}this.autoSearch=false;this.frameRate=0;this.version="";this.name="";this.stage=null;this.frameIndices.length=0;this.cachedFrames.length=0;this.armatureNames.length=0;this.binary=null;this.intArray=null;this.floatArray=null;this.frameIntArray=null;this.frameFloatArray=null;this.frameArray=null;this.timelineArray=null;this.userData=null;};DragonBonesData.prototype.addArmature=function(value){if(value.name in this.armatures){console.warn("Same armature: "+value.name);return;}value.parent=this;this.armatures[value.name]=value;this.armatureNames.push(value.name);};DragonBonesData.prototype.getArmature=function(armatureName){return armatureName in this.armatures?this.armatures[armatureName]:null;};DragonBonesData.prototype.dispose=function(){console.warn("已废弃");this.returnToPool();};return DragonBonesData;}(dragonBones.BaseObject);dragonBones.DragonBonesData=DragonBonesData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var ArmatureData=function(_super){__extends(ArmatureData,_super);function ArmatureData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.aabb=new dragonBones.Rectangle();_this.animationNames=[];_this.sortedBones=[];_this.sortedSlots=[];_this.defaultActions=[];_this.actions=[];_this.bones={};_this.slots={};_this.constraints={};_this.skins={};_this.animations={};_this.canvas=null;_this.userData=null;return _this;}ArmatureData.toString=function(){return "[class dragonBones.ArmatureData]";};ArmatureData.prototype._onClear=function(){for(var _i=0,_a=this.defaultActions;_i<_a.length;_i++){var action=_a[_i];action.returnToPool();}for(var _b=0,_c=this.actions;_b<_c.length;_b++){var action=_c[_b];action.returnToPool();}for(var k in this.bones){this.bones[k].returnToPool();delete this.bones[k];}for(var k in this.slots){this.slots[k].returnToPool();delete this.slots[k];}for(var k in this.constraints){this.constraints[k].returnToPool();delete this.constraints[k];}for(var k in this.skins){this.skins[k].returnToPool();delete this.skins[k];}for(var k in this.animations){this.animations[k].returnToPool();delete this.animations[k];}if(this.canvas!==null){this.canvas.returnToPool();}if(this.userData!==null){this.userData.returnToPool();}this.type=0;this.frameRate=0;this.cacheFrameRate=0;this.scale=1.0;this.name="";this.aabb.clear();this.animationNames.length=0;this.sortedBones.length=0;this.sortedSlots.length=0;this.defaultActions.length=0;this.actions.length=0;this.defaultSkin=null;this.defaultAnimation=null;this.canvas=null;this.userData=null;this.parent=null;};ArmatureData.prototype.sortBones=function(){var total=this.sortedBones.length;if(total<=0){return;}var sortHelper=this.sortedBones.concat();var index=0;var count=0;this.sortedBones.length=0;while(count<total){var bone=sortHelper[index++];if(index>=total){index=0;}if(this.sortedBones.indexOf(bone)>=0){continue;}var flag=false;for(var k in this.constraints){var constraint=this.constraints[k];if(constraint.root===bone&&this.sortedBones.indexOf(constraint.target)<0){flag=true;break;}}if(flag){continue;}if(bone.parent!==null&&this.sortedBones.indexOf(bone.parent)<0){continue;}this.sortedBones.push(bone);count++;}};ArmatureData.prototype.cacheFrames=function(frameRate){if(this.cacheFrameRate>0){return;}this.cacheFrameRate=frameRate;for(var k in this.animations){this.animations[k].cacheFrames(this.cacheFrameRate);}};ArmatureData.prototype.setCacheFrame=function(globalTransformMatrix,transform){var dataArray=this.parent.cachedFrames;var arrayOffset=dataArray.length;dataArray.length+=10;dataArray[arrayOffset]=globalTransformMatrix.a;dataArray[arrayOffset+1]=globalTransformMatrix.b;dataArray[arrayOffset+2]=globalTransformMatrix.c;dataArray[arrayOffset+3]=globalTransformMatrix.d;dataArray[arrayOffset+4]=globalTransformMatrix.tx;dataArray[arrayOffset+5]=globalTransformMatrix.ty;dataArray[arrayOffset+6]=transform.rotation;dataArray[arrayOffset+7]=transform.skew;dataArray[arrayOffset+8]=transform.scaleX;dataArray[arrayOffset+9]=transform.scaleY;return arrayOffset;};ArmatureData.prototype.getCacheFrame=function(globalTransformMatrix,transform,arrayOffset){var dataArray=this.parent.cachedFrames;globalTransformMatrix.a=dataArray[arrayOffset];globalTransformMatrix.b=dataArray[arrayOffset+1];globalTransformMatrix.c=dataArray[arrayOffset+2];globalTransformMatrix.d=dataArray[arrayOffset+3];globalTransformMatrix.tx=dataArray[arrayOffset+4];globalTransformMatrix.ty=dataArray[arrayOffset+5];transform.rotation=dataArray[arrayOffset+6];transform.skew=dataArray[arrayOffset+7];transform.scaleX=dataArray[arrayOffset+8];transform.scaleY=dataArray[arrayOffset+9];transform.x=globalTransformMatrix.tx;transform.y=globalTransformMatrix.ty;};ArmatureData.prototype.addBone=function(value){if(value.name in this.bones){console.warn("Same bone: "+value.name);return;}this.bones[value.name]=value;this.sortedBones.push(value);};ArmatureData.prototype.addSlot=function(value){if(value.name in this.slots){console.warn("Same slot: "+value.name);return;}this.slots[value.name]=value;this.sortedSlots.push(value);};ArmatureData.prototype.addConstraint=function(value){if(value.name in this.constraints){console.warn("Same constraint: "+value.name);return;}this.constraints[value.name]=value;};ArmatureData.prototype.addSkin=function(value){if(value.name in this.skins){console.warn("Same skin: "+value.name);return;}value.parent=this;this.skins[value.name]=value;if(this.defaultSkin===null){this.defaultSkin=value;}if(value.name==="default"){this.defaultSkin=value;}};ArmatureData.prototype.addAnimation=function(value){if(value.name in this.animations){console.warn("Same animation: "+value.name);return;}value.parent=this;this.animations[value.name]=value;this.animationNames.push(value.name);if(this.defaultAnimation===null){this.defaultAnimation=value;}};ArmatureData.prototype.addAction=function(value,isDefault){if(isDefault){this.defaultActions.push(value);}else {this.actions.push(value);}};ArmatureData.prototype.getBone=function(boneName){return boneName in this.bones?this.bones[boneName]:null;};ArmatureData.prototype.getSlot=function(slotName){return slotName in this.slots?this.slots[slotName]:null;};ArmatureData.prototype.getConstraint=function(constraintName){return constraintName in this.constraints?this.constraints[constraintName]:null;};ArmatureData.prototype.getSkin=function(skinName){return skinName in this.skins?this.skins[skinName]:null;};ArmatureData.prototype.getMesh=function(skinName,slotName,meshName){var skin=this.getSkin(skinName);if(skin===null){return null;}return skin.getDisplay(slotName,meshName);};ArmatureData.prototype.getAnimation=function(animationName){return animationName in this.animations?this.animations[animationName]:null;};return ArmatureData;}(dragonBones.BaseObject);dragonBones.ArmatureData=ArmatureData;var BoneData=function(_super){__extends(BoneData,_super);function BoneData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.transform=new dragonBones.Transform();_this.userData=null;return _this;}BoneData.toString=function(){return "[class dragonBones.BoneData]";};BoneData.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool();}this.inheritTranslation=false;this.inheritRotation=false;this.inheritScale=false;this.inheritReflection=false;this.type=0;this.length=0.0;this.name="";this.transform.identity();this.userData=null;this.parent=null;};return BoneData;}(dragonBones.BaseObject);dragonBones.BoneData=BoneData;var SurfaceData=function(_super){__extends(SurfaceData,_super);function SurfaceData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];return _this;}SurfaceData.toString=function(){return "[class dragonBones.SurfaceData]";};SurfaceData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=1;this.segmentX=0;this.segmentY=0;this.vertices.length=0;};return SurfaceData;}(BoneData);dragonBones.SurfaceData=SurfaceData;var SlotData=function(_super){__extends(SlotData,_super);function SlotData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.color=null;_this.userData=null;return _this;}SlotData.createColor=function(){return new dragonBones.ColorTransform();};SlotData.toString=function(){return "[class dragonBones.SlotData]";};SlotData.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool();}this.blendMode=0;this.displayIndex=0;this.zOrder=0;this.name="";this.color=null;this.userData=null;this.parent=null;};SlotData.DEFAULT_COLOR=new dragonBones.ColorTransform();return SlotData;}(dragonBones.BaseObject);dragonBones.SlotData=SlotData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var ConstraintData=function(_super){__extends(ConstraintData,_super);function ConstraintData(){return _super!==null&&_super.apply(this,arguments)||this;}ConstraintData.prototype._onClear=function(){this.order=0;this.name="";this.type=0;this.target=null;this.root=null;this.bone=null;};return ConstraintData;}(dragonBones.BaseObject);dragonBones.ConstraintData=ConstraintData;var IKConstraintData=function(_super){__extends(IKConstraintData,_super);function IKConstraintData(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraintData.toString=function(){return "[class dragonBones.IKConstraintData]";};IKConstraintData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.scaleEnabled=false;this.bendPositive=false;this.weight=1.0;};return IKConstraintData;}(ConstraintData);dragonBones.IKConstraintData=IKConstraintData;var PathConstraintData=function(_super){__extends(PathConstraintData,_super);function PathConstraintData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.bones=[];return _this;}PathConstraintData.toString=function(){return "[class dragonBones.PathConstraintData]";};PathConstraintData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.pathSlot=null;this.pathDisplayData=null;this.bones.length=0;this.positionMode=0;this.spacingMode=1;this.rotateMode=1;this.position=0.0;this.spacing=0.0;this.rotateOffset=0.0;this.rotateMix=0.0;this.translateMix=0.0;};PathConstraintData.prototype.AddBone=function(value){this.bones.push(value);};return PathConstraintData;}(ConstraintData);dragonBones.PathConstraintData=PathConstraintData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var CanvasData=function(_super){__extends(CanvasData,_super);function CanvasData(){return _super!==null&&_super.apply(this,arguments)||this;}CanvasData.toString=function(){return "[class dragonBones.CanvasData]";};CanvasData.prototype._onClear=function(){this.hasBackground=false;this.color=0x000000;this.x=0;this.y=0;this.width=0;this.height=0;};return CanvasData;}(dragonBones.BaseObject);dragonBones.CanvasData=CanvasData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var SkinData=function(_super){__extends(SkinData,_super);function SkinData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.displays={};return _this;}SkinData.toString=function(){return "[class dragonBones.SkinData]";};SkinData.prototype._onClear=function(){for(var k in this.displays){var slotDisplays=this.displays[k];for(var _i=0,slotDisplays_1=slotDisplays;_i<slotDisplays_1.length;_i++){var display=slotDisplays_1[_i];if(display!==null){display.returnToPool();}}delete this.displays[k];}this.name="";this.parent=null;};SkinData.prototype.addDisplay=function(slotName,value){if(!(slotName in this.displays)){this.displays[slotName]=[];}if(value!==null){value.parent=this;}var slotDisplays=this.displays[slotName];slotDisplays.push(value);};SkinData.prototype.getDisplay=function(slotName,displayName){var slotDisplays=this.getDisplays(slotName);if(slotDisplays!==null){for(var _i=0,slotDisplays_2=slotDisplays;_i<slotDisplays_2.length;_i++){var display=slotDisplays_2[_i];if(display!==null&&display.name===displayName){return display;}}}return null;};SkinData.prototype.getDisplays=function(slotName){if(!(slotName in this.displays)){return null;}return this.displays[slotName];};return SkinData;}(dragonBones.BaseObject);dragonBones.SkinData=SkinData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var VerticesData=function(){function VerticesData(){this.weight=null;}VerticesData.prototype.clear=function(){if(!this.isShared&&this.weight!==null){this.weight.returnToPool();}this.isShared=false;this.inheritDeform=false;this.offset=0;this.data=null;this.weight=null;};VerticesData.prototype.shareFrom=function(value){this.isShared=true;this.offset=value.offset;this.weight=value.weight;};return VerticesData;}();dragonBones.VerticesData=VerticesData;var DisplayData=function(_super){__extends(DisplayData,_super);function DisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.transform=new dragonBones.Transform();return _this;}DisplayData.prototype._onClear=function(){this.name="";this.path="";this.transform.identity();this.parent=null;};return DisplayData;}(dragonBones.BaseObject);dragonBones.DisplayData=DisplayData;var ImageDisplayData=function(_super){__extends(ImageDisplayData,_super);function ImageDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.pivot=new dragonBones.Point();return _this;}ImageDisplayData.toString=function(){return "[class dragonBones.ImageDisplayData]";};ImageDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=0;this.pivot.clear();this.texture=null;};return ImageDisplayData;}(DisplayData);dragonBones.ImageDisplayData=ImageDisplayData;var ArmatureDisplayData=function(_super){__extends(ArmatureDisplayData,_super);function ArmatureDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.actions=[];return _this;}ArmatureDisplayData.toString=function(){return "[class dragonBones.ArmatureDisplayData]";};ArmatureDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);for(var _i=0,_a=this.actions;_i<_a.length;_i++){var action=_a[_i];action.returnToPool();}this.type=1;this.inheritAnimation=false;this.actions.length=0;this.armature=null;};ArmatureDisplayData.prototype.addAction=function(value){this.actions.push(value);};return ArmatureDisplayData;}(DisplayData);dragonBones.ArmatureDisplayData=ArmatureDisplayData;var MeshDisplayData=function(_super){__extends(MeshDisplayData,_super);function MeshDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=new VerticesData();return _this;}MeshDisplayData.toString=function(){return "[class dragonBones.MeshDisplayData]";};MeshDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=2;this.vertices.clear();this.texture=null;};return MeshDisplayData;}(DisplayData);dragonBones.MeshDisplayData=MeshDisplayData;var BoundingBoxDisplayData=function(_super){__extends(BoundingBoxDisplayData,_super);function BoundingBoxDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.boundingBox=null;return _this;}BoundingBoxDisplayData.toString=function(){return "[class dragonBones.BoundingBoxDisplayData]";};BoundingBoxDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);if(this.boundingBox!==null){this.boundingBox.returnToPool();}this.type=3;this.boundingBox=null;};return BoundingBoxDisplayData;}(DisplayData);dragonBones.BoundingBoxDisplayData=BoundingBoxDisplayData;var PathDisplayData=function(_super){__extends(PathDisplayData,_super);function PathDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=new VerticesData();_this.curveLengths=[];return _this;}PathDisplayData.toString=function(){return "[class dragonBones.PathDisplayData]";};PathDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=4;this.closed=false;this.constantSpeed=false;this.vertices.clear();this.curveLengths.length=0;};return PathDisplayData;}(DisplayData);dragonBones.PathDisplayData=PathDisplayData;var WeightData=function(_super){__extends(WeightData,_super);function WeightData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.bones=[];return _this;}WeightData.toString=function(){return "[class dragonBones.WeightData]";};WeightData.prototype._onClear=function(){this.count=0;this.offset=0;this.bones.length=0;};WeightData.prototype.addBone=function(value){this.bones.push(value);};return WeightData;}(dragonBones.BaseObject);dragonBones.WeightData=WeightData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var BoundingBoxData=function(_super){__extends(BoundingBoxData,_super);function BoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}BoundingBoxData.prototype._onClear=function(){this.color=0x000000;this.width=0.0;this.height=0.0;};return BoundingBoxData;}(dragonBones.BaseObject);dragonBones.BoundingBoxData=BoundingBoxData;var RectangleBoundingBoxData=function(_super){__extends(RectangleBoundingBoxData,_super);function RectangleBoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}RectangleBoundingBoxData.toString=function(){return "[class dragonBones.RectangleBoundingBoxData]";};RectangleBoundingBoxData._computeOutCode=function(x,y,xMin,yMin,xMax,yMax){var code=0;if(x<xMin){code|=1;}else if(x>xMax){code|=2;}if(y<yMin){code|=4;}else if(y>yMax){code|=8;}return code;};RectangleBoundingBoxData.rectangleIntersectsSegment=function(xA,yA,xB,yB,xMin,yMin,xMax,yMax,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var inSideA=xA>xMin&&xA<xMax&&yA>yMin&&yA<yMax;var inSideB=xB>xMin&&xB<xMax&&yB>yMin&&yB<yMax;if(inSideA&&inSideB){return -1;}var intersectionCount=0;var outcode0=RectangleBoundingBoxData._computeOutCode(xA,yA,xMin,yMin,xMax,yMax);var outcode1=RectangleBoundingBoxData._computeOutCode(xB,yB,xMin,yMin,xMax,yMax);while(true){if((outcode0|outcode1)===0){intersectionCount=2;break;}else if((outcode0&outcode1)!==0){break;}var x=0.0;var y=0.0;var normalRadian=0.0;var outcodeOut=outcode0!==0?outcode0:outcode1;if((outcodeOut&4)!==0){x=xA+(xB-xA)*(yMin-yA)/(yB-yA);y=yMin;if(normalRadians!==null){normalRadian=-Math.PI*0.5;}}else if((outcodeOut&8)!==0){x=xA+(xB-xA)*(yMax-yA)/(yB-yA);y=yMax;if(normalRadians!==null){normalRadian=Math.PI*0.5;}}else if((outcodeOut&2)!==0){y=yA+(yB-yA)*(xMax-xA)/(xB-xA);x=xMax;if(normalRadians!==null){normalRadian=0;}}else if((outcodeOut&1)!==0){y=yA+(yB-yA)*(xMin-xA)/(xB-xA);x=xMin;if(normalRadians!==null){normalRadian=Math.PI;}}if(outcodeOut===outcode0){xA=x;yA=y;outcode0=RectangleBoundingBoxData._computeOutCode(xA,yA,xMin,yMin,xMax,yMax);if(normalRadians!==null){normalRadians.x=normalRadian;}}else {xB=x;yB=y;outcode1=RectangleBoundingBoxData._computeOutCode(xB,yB,xMin,yMin,xMax,yMax);if(normalRadians!==null){normalRadians.y=normalRadian;}}}if(intersectionCount){if(inSideA){intersectionCount=2;if(intersectionPointA!==null){intersectionPointA.x=xB;intersectionPointA.y=yB;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=xB;}if(normalRadians!==null){normalRadians.x=normalRadians.y+Math.PI;}}else if(inSideB){intersectionCount=1;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xA;intersectionPointB.y=yA;}if(normalRadians!==null){normalRadians.y=normalRadians.x+Math.PI;}}else {intersectionCount=3;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=yB;}}}return intersectionCount;};RectangleBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=0;};RectangleBoundingBoxData.prototype.containsPoint=function(pX,pY){var widthH=this.width*0.5;if(pX>=-widthH&&pX<=widthH){var heightH=this.height*0.5;if(pY>=-heightH&&pY<=heightH){return true;}}return false;};RectangleBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var widthH=this.width*0.5;var heightH=this.height*0.5;var intersectionCount=RectangleBoundingBoxData.rectangleIntersectsSegment(xA,yA,xB,yB,-widthH,-heightH,widthH,heightH,intersectionPointA,intersectionPointB,normalRadians);return intersectionCount;};return RectangleBoundingBoxData;}(BoundingBoxData);dragonBones.RectangleBoundingBoxData=RectangleBoundingBoxData;var EllipseBoundingBoxData=function(_super){__extends(EllipseBoundingBoxData,_super);function EllipseBoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}EllipseBoundingBoxData.toString=function(){return "[class dragonBones.EllipseData]";};EllipseBoundingBoxData.ellipseIntersectsSegment=function(xA,yA,xB,yB,xC,yC,widthH,heightH,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var d=widthH/heightH;var dd=d*d;yA*=d;yB*=d;var dX=xB-xA;var dY=yB-yA;var lAB=Math.sqrt(dX*dX+dY*dY);var xD=dX/lAB;var yD=dY/lAB;var a=(xC-xA)*xD+(yC-yA)*yD;var aa=a*a;var ee=xA*xA+yA*yA;var rr=widthH*widthH;var dR=rr-ee+aa;var intersectionCount=0;if(dR>=0.0){var dT=Math.sqrt(dR);var sA=a-dT;var sB=a+dT;var inSideA=sA<0.0?-1:sA<=lAB?0:1;var inSideB=sB<0.0?-1:sB<=lAB?0:1;var sideAB=inSideA*inSideB;if(sideAB<0){return -1;}else if(sideAB===0){if(inSideA===-1){intersectionCount=2;xB=xA+sB*xD;yB=(yA+sB*yD)/d;if(intersectionPointA!==null){intersectionPointA.x=xB;intersectionPointA.y=yB;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=yB;}if(normalRadians!==null){normalRadians.x=Math.atan2(yB/rr*dd,xB/rr);normalRadians.y=normalRadians.x+Math.PI;}}else if(inSideB===1){intersectionCount=1;xA=xA+sA*xD;yA=(yA+sA*yD)/d;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xA;intersectionPointB.y=yA;}if(normalRadians!==null){normalRadians.x=Math.atan2(yA/rr*dd,xA/rr);normalRadians.y=normalRadians.x+Math.PI;}}else {intersectionCount=3;if(intersectionPointA!==null){intersectionPointA.x=xA+sA*xD;intersectionPointA.y=(yA+sA*yD)/d;if(normalRadians!==null){normalRadians.x=Math.atan2(intersectionPointA.y/rr*dd,intersectionPointA.x/rr);}}if(intersectionPointB!==null){intersectionPointB.x=xA+sB*xD;intersectionPointB.y=(yA+sB*yD)/d;if(normalRadians!==null){normalRadians.y=Math.atan2(intersectionPointB.y/rr*dd,intersectionPointB.x/rr);}}}}}return intersectionCount;};EllipseBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=1;};EllipseBoundingBoxData.prototype.containsPoint=function(pX,pY){var widthH=this.width*0.5;if(pX>=-widthH&&pX<=widthH){var heightH=this.height*0.5;if(pY>=-heightH&&pY<=heightH){pY*=widthH/heightH;return Math.sqrt(pX*pX+pY*pY)<=widthH;}}return false;};EllipseBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var intersectionCount=EllipseBoundingBoxData.ellipseIntersectsSegment(xA,yA,xB,yB,0.0,0.0,this.width*0.5,this.height*0.5,intersectionPointA,intersectionPointB,normalRadians);return intersectionCount;};return EllipseBoundingBoxData;}(BoundingBoxData);dragonBones.EllipseBoundingBoxData=EllipseBoundingBoxData;var PolygonBoundingBoxData=function(_super){__extends(PolygonBoundingBoxData,_super);function PolygonBoundingBoxData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];return _this;}PolygonBoundingBoxData.toString=function(){return "[class dragonBones.PolygonBoundingBoxData]";};PolygonBoundingBoxData.polygonIntersectsSegment=function(xA,yA,xB,yB,vertices,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}if(xA===xB){xA=xB+0.000001;}if(yA===yB){yA=yB+0.000001;}var count=vertices.length;var dXAB=xA-xB;var dYAB=yA-yB;var llAB=xA*yB-yA*xB;var intersectionCount=0;var xC=vertices[count-2];var yC=vertices[count-1];var dMin=0.0;var dMax=0.0;var xMin=0.0;var yMin=0.0;var xMax=0.0;var yMax=0.0;for(var i=0;i<count;i+=2){var xD=vertices[i];var yD=vertices[i+1];if(xC===xD){xC=xD+0.0001;}if(yC===yD){yC=yD+0.0001;}var dXCD=xC-xD;var dYCD=yC-yD;var llCD=xC*yD-yC*xD;var ll=dXAB*dYCD-dYAB*dXCD;var x=(llAB*dXCD-dXAB*llCD)/ll;if((x>=xC&&x<=xD||x>=xD&&x<=xC)&&(dXAB===0.0||x>=xA&&x<=xB||x>=xB&&x<=xA)){var y=(llAB*dYCD-dYAB*llCD)/ll;if((y>=yC&&y<=yD||y>=yD&&y<=yC)&&(dYAB===0.0||y>=yA&&y<=yB||y>=yB&&y<=yA)){if(intersectionPointB!==null){var d=x-xA;if(d<0.0){d=-d;}if(intersectionCount===0){dMin=d;dMax=d;xMin=x;yMin=y;xMax=x;yMax=y;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;normalRadians.y=normalRadians.x;}}else {if(d<dMin){dMin=d;xMin=x;yMin=y;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;}}if(d>dMax){dMax=d;xMax=x;yMax=y;if(normalRadians!==null){normalRadians.y=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;}}}intersectionCount++;}else {xMin=x;yMin=y;xMax=x;yMax=y;intersectionCount++;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;normalRadians.y=normalRadians.x;}break;}}}xC=xD;yC=yD;}if(intersectionCount===1){if(intersectionPointA!==null){intersectionPointA.x=xMin;intersectionPointA.y=yMin;}if(intersectionPointB!==null){intersectionPointB.x=xMin;intersectionPointB.y=yMin;}if(normalRadians!==null){normalRadians.y=normalRadians.x+Math.PI;}}else if(intersectionCount>1){intersectionCount++;if(intersectionPointA!==null){intersectionPointA.x=xMin;intersectionPointA.y=yMin;}if(intersectionPointB!==null){intersectionPointB.x=xMax;intersectionPointB.y=yMax;}}return intersectionCount;};PolygonBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=2;this.x=0.0;this.y=0.0;this.vertices.length=0;};PolygonBoundingBoxData.prototype.containsPoint=function(pX,pY){var isInSide=false;if(pX>=this.x&&pX<=this.width&&pY>=this.y&&pY<=this.height){for(var i=0,l=this.vertices.length,iP=l-2;i<l;i+=2){var yA=this.vertices[iP+1];var yB=this.vertices[i+1];if(yB<pY&&yA>=pY||yA<pY&&yB>=pY){var xA=this.vertices[iP];var xB=this.vertices[i];if((pY-yB)*(xA-xB)/(yA-yB)+xB<pX){isInSide=!isInSide;}}iP=i;}}return isInSide;};PolygonBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var intersectionCount=0;if(RectangleBoundingBoxData.rectangleIntersectsSegment(xA,yA,xB,yB,this.x,this.y,this.x+this.width,this.y+this.height,null,null,null)!==0){intersectionCount=PolygonBoundingBoxData.polygonIntersectsSegment(xA,yA,xB,yB,this.vertices,intersectionPointA,intersectionPointB,normalRadians);}return intersectionCount;};return PolygonBoundingBoxData;}(BoundingBoxData);dragonBones.PolygonBoundingBoxData=PolygonBoundingBoxData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var AnimationData=function(_super){__extends(AnimationData,_super);function AnimationData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cachedFrames=[];_this.boneTimelines={};_this.surfaceTimelines={};_this.slotTimelines={};_this.constraintTimelines={};_this.animationTimelines={};_this.boneCachedFrameIndices={};_this.slotCachedFrameIndices={};_this.actionTimeline=null;_this.zOrderTimeline=null;return _this;}AnimationData.toString=function(){return "[class dragonBones.AnimationData]";};AnimationData.prototype._onClear=function(){for(var k in this.boneTimelines){for(var _i=0,_a=this.boneTimelines[k];_i<_a.length;_i++){var timeline=_a[_i];timeline.returnToPool();}delete this.boneTimelines[k];}for(var k in this.surfaceTimelines){for(var _b=0,_c=this.surfaceTimelines[k];_b<_c.length;_b++){var timeline=_c[_b];timeline.returnToPool();}delete this.surfaceTimelines[k];}for(var k in this.slotTimelines){for(var _d=0,_e=this.slotTimelines[k];_d<_e.length;_d++){var timeline=_e[_d];timeline.returnToPool();}delete this.slotTimelines[k];}for(var k in this.constraintTimelines){for(var _f=0,_g=this.constraintTimelines[k];_f<_g.length;_f++){var timeline=_g[_f];timeline.returnToPool();}delete this.constraintTimelines[k];}for(var k in this.animationTimelines){for(var _h=0,_j=this.animationTimelines[k];_h<_j.length;_h++){var timeline=_j[_h];timeline.returnToPool();}delete this.animationTimelines[k];}for(var k in this.boneCachedFrameIndices){delete this.boneCachedFrameIndices[k];}for(var k in this.slotCachedFrameIndices){delete this.slotCachedFrameIndices[k];}if(this.actionTimeline!==null){this.actionTimeline.returnToPool();}if(this.zOrderTimeline!==null){this.zOrderTimeline.returnToPool();}this.frameIntOffset=0;this.frameFloatOffset=0;this.frameOffset=0;this.frameCount=0;this.playTimes=0;this.duration=0.0;this.scale=1.0;this.fadeInTime=0.0;this.cacheFrameRate=0.0;this.name="";this.cachedFrames.length=0;this.actionTimeline=null;this.zOrderTimeline=null;this.parent=null;};AnimationData.prototype.cacheFrames=function(frameRate){if(this.cacheFrameRate>0.0){return;}this.cacheFrameRate=Math.max(Math.ceil(frameRate*this.scale),1.0);var cacheFrameCount=Math.ceil(this.cacheFrameRate*this.duration)+1;this.cachedFrames.length=cacheFrameCount;for(var i=0,l=this.cacheFrames.length;i<l;++i){this.cachedFrames[i]=false;}for(var _i=0,_a=this.parent.sortedBones;_i<_a.length;_i++){var bone=_a[_i];var indices=new Array(cacheFrameCount);for(var i=0,l=indices.length;i<l;++i){indices[i]=-1;}this.boneCachedFrameIndices[bone.name]=indices;}for(var _b=0,_c=this.parent.sortedSlots;_b<_c.length;_b++){var slot=_c[_b];var indices=new Array(cacheFrameCount);for(var i=0,l=indices.length;i<l;++i){indices[i]=-1;}this.slotCachedFrameIndices[slot.name]=indices;}};AnimationData.prototype.addBoneTimeline=function(bone,timeline){var timelines=bone.name in this.boneTimelines?this.boneTimelines[bone.name]:this.boneTimelines[bone.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addSurfaceTimeline=function(surface,timeline){var timelines=surface.name in this.surfaceTimelines?this.surfaceTimelines[surface.name]:this.surfaceTimelines[surface.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addSlotTimeline=function(slot,timeline){var timelines=slot.name in this.slotTimelines?this.slotTimelines[slot.name]:this.slotTimelines[slot.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addConstraintTimeline=function(constraint,timeline){var timelines=constraint.name in this.constraintTimelines?this.constraintTimelines[constraint.name]:this.constraintTimelines[constraint.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addAnimationTimeline=function(timelineName,timeline){var timelines=timelineName in this.animationTimelines?this.animationTimelines[timelineName]:this.animationTimelines[timelineName]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.getBoneTimelines=function(timelineName){return timelineName in this.boneTimelines?this.boneTimelines[timelineName]:null;};AnimationData.prototype.getSurfaceTimelines=function(timelineName){return timelineName in this.surfaceTimelines?this.surfaceTimelines[timelineName]:null;};AnimationData.prototype.getSlotTimelines=function(timelineName){return timelineName in this.slotTimelines?this.slotTimelines[timelineName]:null;};AnimationData.prototype.getConstraintTimelines=function(timelineName){return timelineName in this.constraintTimelines?this.constraintTimelines[timelineName]:null;};AnimationData.prototype.getAnimationTimelines=function(timelineName){return timelineName in this.animationTimelines?this.animationTimelines[timelineName]:null;};AnimationData.prototype.getBoneCachedFrameIndices=function(boneName){return boneName in this.boneCachedFrameIndices?this.boneCachedFrameIndices[boneName]:null;};AnimationData.prototype.getSlotCachedFrameIndices=function(slotName){return slotName in this.slotCachedFrameIndices?this.slotCachedFrameIndices[slotName]:null;};return AnimationData;}(dragonBones.BaseObject);dragonBones.AnimationData=AnimationData;var TimelineData=function(_super){__extends(TimelineData,_super);function TimelineData(){return _super!==null&&_super.apply(this,arguments)||this;}TimelineData.toString=function(){return "[class dragonBones.TimelineData]";};TimelineData.prototype._onClear=function(){this.type=10;this.offset=0;this.frameIndicesOffset=-1;};return TimelineData;}(dragonBones.BaseObject);dragonBones.TimelineData=TimelineData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var AnimationConfig=function(_super){__extends(AnimationConfig,_super);function AnimationConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.boneMask=[];return _this;}AnimationConfig.toString=function(){return "[class dragonBones.AnimationConfig]";};AnimationConfig.prototype._onClear=function(){this.pauseFadeOut=true;this.fadeOutMode=4;this.fadeOutTweenType=1;this.fadeOutTime=-1.0;this.actionEnabled=true;this.additiveBlending=false;this.displayControl=true;this.pauseFadeIn=true;this.resetToPose=true;this.fadeInTweenType=1;this.playTimes=-1;this.layer=0;this.position=0.0;this.duration=-1.0;this.timeScale=-100.0;this.weight=1.0;this.fadeInTime=-1.0;this.autoFadeOutTime=-1.0;this.name="";this.animation="";this.group="";this.boneMask.length=0;};AnimationConfig.prototype.clear=function(){this._onClear();};AnimationConfig.prototype.copyFrom=function(value){this.pauseFadeOut=value.pauseFadeOut;this.fadeOutMode=value.fadeOutMode;this.autoFadeOutTime=value.autoFadeOutTime;this.fadeOutTweenType=value.fadeOutTweenType;this.actionEnabled=value.actionEnabled;this.additiveBlending=value.additiveBlending;this.displayControl=value.displayControl;this.pauseFadeIn=value.pauseFadeIn;this.resetToPose=value.resetToPose;this.playTimes=value.playTimes;this.layer=value.layer;this.position=value.position;this.duration=value.duration;this.timeScale=value.timeScale;this.fadeInTime=value.fadeInTime;this.fadeOutTime=value.fadeOutTime;this.fadeInTweenType=value.fadeInTweenType;this.weight=value.weight;this.name=value.name;this.animation=value.animation;this.group=value.group;this.boneMask.length=value.boneMask.length;for(var i=0,l=this.boneMask.length;i<l;++i){this.boneMask[i]=value.boneMask[i];}};AnimationConfig.prototype.containsBoneMask=function(boneName){return this.boneMask.length===0||this.boneMask.indexOf(boneName)>=0;};AnimationConfig.prototype.addBoneMask=function(armature,boneName,recursive){if(recursive===void 0){recursive=true;}var currentBone=armature.getBone(boneName);if(currentBone===null){return;}if(this.boneMask.indexOf(boneName)<0){this.boneMask.push(boneName);}if(recursive){for(var _i=0,_a=armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(this.boneMask.indexOf(bone.name)<0&&currentBone.contains(bone)){this.boneMask.push(bone.name);}}}};AnimationConfig.prototype.removeBoneMask=function(armature,boneName,recursive){if(recursive===void 0){recursive=true;}var index=this.boneMask.indexOf(boneName);if(index>=0){this.boneMask.splice(index,1);}if(recursive){var currentBone=armature.getBone(boneName);if(currentBone!==null){if(this.boneMask.length>0){for(var _i=0,_a=armature.getBones();_i<_a.length;_i++){var bone=_a[_i];var index_1=this.boneMask.indexOf(bone.name);if(index_1>=0&&currentBone.contains(bone)){this.boneMask.splice(index_1,1);}}}else {for(var _b=0,_c=armature.getBones();_b<_c.length;_b++){var bone=_c[_b];if(bone===currentBone){continue;}if(!currentBone.contains(bone)){this.boneMask.push(bone.name);}}}}}};return AnimationConfig;}(dragonBones.BaseObject);dragonBones.AnimationConfig=AnimationConfig;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var TextureAtlasData=function(_super){__extends(TextureAtlasData,_super);function TextureAtlasData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.textures={};return _this;}TextureAtlasData.prototype._onClear=function(){for(var k in this.textures){this.textures[k].returnToPool();delete this.textures[k];}this.autoSearch=false;this.width=0;this.height=0;this.scale=1.0;this.name="";this.imagePath="";};TextureAtlasData.prototype.copyFrom=function(value){this.autoSearch=value.autoSearch;this.scale=value.scale;this.width=value.width;this.height=value.height;this.name=value.name;this.imagePath=value.imagePath;for(var k in this.textures){this.textures[k].returnToPool();delete this.textures[k];}for(var k in value.textures){var texture=this.createTexture();texture.copyFrom(value.textures[k]);this.textures[k]=texture;}};TextureAtlasData.prototype.addTexture=function(value){if(value.name in this.textures){console.warn("Same texture: "+value.name);return;}value.parent=this;this.textures[value.name]=value;};TextureAtlasData.prototype.getTexture=function(textureName){return textureName in this.textures?this.textures[textureName]:null;};return TextureAtlasData;}(dragonBones.BaseObject);dragonBones.TextureAtlasData=TextureAtlasData;var TextureData=function(_super){__extends(TextureData,_super);function TextureData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.region=new dragonBones.Rectangle();_this.frame=null;return _this;}TextureData.createRectangle=function(){return new dragonBones.Rectangle();};TextureData.prototype._onClear=function(){this.rotated=false;this.name="";this.region.clear();this.parent=null;this.frame=null;};TextureData.prototype.copyFrom=function(value){this.rotated=value.rotated;this.name=value.name;this.region.copyFrom(value.region);this.parent=value.parent;if(this.frame===null&&value.frame!==null){this.frame=TextureData.createRectangle();}else if(this.frame!==null&&value.frame===null){this.frame=null;}if(this.frame!==null&&value.frame!==null){this.frame.copyFrom(value.frame);}};return TextureData;}(dragonBones.BaseObject);dragonBones.TextureData=TextureData;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var DeformVertices=function(_super){__extends(DeformVertices,_super);function DeformVertices(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];_this.bones=[];return _this;}DeformVertices.toString=function(){return "[class dragonBones.DeformVertices]";};DeformVertices.prototype._onClear=function(){this.verticesDirty=false;this.vertices.length=0;this.bones.length=0;this.verticesData=null;};DeformVertices.prototype.init=function(verticesDataValue,armature){this.verticesData=verticesDataValue;if(this.verticesData!==null){var vertexCount=0;if(this.verticesData.weight!==null){vertexCount=this.verticesData.weight.count*2;}else {vertexCount=this.verticesData.data.intArray[this.verticesData.offset+0]*2;}this.verticesDirty=true;this.vertices.length=vertexCount;this.bones.length=0;for(var i=0,l=this.vertices.length;i<l;++i){this.vertices[i]=0.0;}if(this.verticesData.weight!==null){for(var i=0,l=this.verticesData.weight.bones.length;i<l;++i){var bone=armature.getBone(this.verticesData.weight.bones[i].name);this.bones.push(bone);}}}else {this.verticesDirty=false;this.vertices.length=0;this.bones.length=0;this.verticesData=null;}};DeformVertices.prototype.isBonesUpdate=function(){for(var _i=0,_a=this.bones;_i<_a.length;_i++){var bone=_a[_i];if(bone!==null&&bone._childrenTransformDirty){return true;}}return false;};return DeformVertices;}(dragonBones.BaseObject);dragonBones.DeformVertices=DeformVertices;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones_1){var Armature=function(_super){__extends(Armature,_super);function Armature(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._bones=[];_this._slots=[];_this._constraints=[];_this._actions=[];_this._animation=null;_this._proxy=null;_this._replaceTextureAtlasData=null;_this._clock=null;return _this;}Armature.toString=function(){return "[class dragonBones.Armature]";};Armature._onSortSlots=function(a,b){return a._zOrder>b._zOrder?1:-1;};Armature.prototype._onClear=function(){if(this._clock!==null){this._clock.remove(this);}for(var _i=0,_a=this._bones;_i<_a.length;_i++){var bone=_a[_i];bone.returnToPool();}for(var _b=0,_c=this._slots;_b<_c.length;_b++){var slot=_c[_b];slot.returnToPool();}for(var _d=0,_e=this._constraints;_d<_e.length;_d++){var constraint=_e[_d];constraint.returnToPool();}for(var _f=0,_g=this._actions;_f<_g.length;_f++){var action=_g[_f];action.returnToPool();}if(this._animation!==null){this._animation.returnToPool();}if(this._proxy!==null){this._proxy.dbClear();}if(this._replaceTextureAtlasData!==null){this._replaceTextureAtlasData.returnToPool();}this.inheritAnimation=true;this.userData=null;this._lockUpdate=false;this._slotsDirty=true;this._zOrderDirty=false;this._flipX=false;this._flipY=false;this._cacheFrameIndex=-1;this._bones.length=0;this._slots.length=0;this._constraints.length=0;this._actions.length=0;this._armatureData=null;this._animation=null;this._proxy=null;this._display=null;this._replaceTextureAtlasData=null;this._replacedTexture=null;this._dragonBones=null;this._clock=null;this._parent=null;};Armature.prototype._sortZOrder=function(slotIndices,offset){var slotDatas=this._armatureData.sortedSlots;var isOriginal=slotIndices===null;if(this._zOrderDirty||!isOriginal){for(var i=0,l=slotDatas.length;i<l;++i){var slotIndex=isOriginal?i:slotIndices[offset+i];if(slotIndex<0||slotIndex>=l){continue;}var slotData=slotDatas[slotIndex];var slot=this.getSlot(slotData.name);if(slot!==null){slot._setZorder(i);}}this._slotsDirty=true;this._zOrderDirty=!isOriginal;}};Armature.prototype._addBone=function(value){if(this._bones.indexOf(value)<0){this._bones.push(value);}};Armature.prototype._addSlot=function(value){if(this._slots.indexOf(value)<0){this._slots.push(value);}};Armature.prototype._addConstraint=function(value){if(this._constraints.indexOf(value)<0){this._constraints.push(value);}};Armature.prototype._bufferAction=function(action,append){if(this._actions.indexOf(action)<0){if(append){this._actions.push(action);}else {this._actions.unshift(action);}}};Armature.prototype.dispose=function(){if(this._armatureData!==null){this._lockUpdate=true;this._dragonBones.bufferObject(this);}};Armature.prototype.init=function(armatureData,proxy,display,dragonBones){if(this._armatureData!==null){return;}this._armatureData=armatureData;this._animation=dragonBones_1.BaseObject.borrowObject(dragonBones_1.Animation);this._proxy=proxy;this._display=display;this._dragonBones=dragonBones;this._proxy.dbInit(this);this._animation.init(this);this._animation.animations=this._armatureData.animations;};Armature.prototype.advanceTime=function(passedTime){if(this._lockUpdate){return;}if(this._armatureData===null){console.warn("The armature has been disposed.");return;}else if(this._armatureData.parent===null){console.warn("The armature data has been disposed.\nPlease make sure dispose armature before call factory.clear().");return;}var prevCacheFrameIndex=this._cacheFrameIndex;this._animation.advanceTime(passedTime);if(this._slotsDirty){this._slotsDirty=false;this._slots.sort(Armature._onSortSlots);}if(this._cacheFrameIndex<0||this._cacheFrameIndex!==prevCacheFrameIndex){var i=0,l=0;for(i=0,l=this._bones.length;i<l;++i){this._bones[i].update(this._cacheFrameIndex);}for(i=0,l=this._slots.length;i<l;++i){this._slots[i].update(this._cacheFrameIndex);}}if(this._actions.length>0){this._lockUpdate=true;for(var _i=0,_a=this._actions;_i<_a.length;_i++){var action=_a[_i];var actionData=action.actionData;if(actionData!==null){if(actionData.type===0){if(action.slot!==null){var childArmature=action.slot.childArmature;if(childArmature!==null){childArmature.animation.fadeIn(actionData.name);}}else if(action.bone!==null){for(var _b=0,_c=this.getSlots();_b<_c.length;_b++){var slot=_c[_b];if(slot.parent===action.bone){var childArmature=slot.childArmature;if(childArmature!==null){childArmature.animation.fadeIn(actionData.name);}}}}else {this._animation.fadeIn(actionData.name);}}}action.returnToPool();}this._actions.length=0;this._lockUpdate=false;}this._proxy.dbUpdate();};Armature.prototype.invalidUpdate=function(boneName,updateSlot){if(boneName===void 0){boneName=null;}if(updateSlot===void 0){updateSlot=false;}if(boneName!==null&&boneName.length>0){var bone=this.getBone(boneName);if(bone!==null){bone.invalidUpdate();if(updateSlot){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===bone){slot.invalidUpdate();}}}}}else {for(var _b=0,_c=this._bones;_b<_c.length;_b++){var bone=_c[_b];bone.invalidUpdate();}if(updateSlot){for(var _d=0,_e=this._slots;_d<_e.length;_d++){var slot=_e[_d];slot.invalidUpdate();}}}};Armature.prototype.containsPoint=function(x,y){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.containsPoint(x,y)){return slot;}}return null;};Armature.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var isV=xA===xB;var dMin=0.0;var dMax=0.0;var intXA=0.0;var intYA=0.0;var intXB=0.0;var intYB=0.0;var intAN=0.0;var intBN=0.0;var intSlotA=null;var intSlotB=null;for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var intersectionCount=slot.intersectsSegment(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians);if(intersectionCount>0){if(intersectionPointA!==null||intersectionPointB!==null){if(intersectionPointA!==null){var d=isV?intersectionPointA.y-yA:intersectionPointA.x-xA;if(d<0.0){d=-d;}if(intSlotA===null||d<dMin){dMin=d;intXA=intersectionPointA.x;intYA=intersectionPointA.y;intSlotA=slot;if(normalRadians){intAN=normalRadians.x;}}}if(intersectionPointB!==null){var d=intersectionPointB.x-xA;if(d<0.0){d=-d;}if(intSlotB===null||d>dMax){dMax=d;intXB=intersectionPointB.x;intYB=intersectionPointB.y;intSlotB=slot;if(normalRadians!==null){intBN=normalRadians.y;}}}}else {intSlotA=slot;break;}}}if(intSlotA!==null&&intersectionPointA!==null){intersectionPointA.x=intXA;intersectionPointA.y=intYA;if(normalRadians!==null){normalRadians.x=intAN;}}if(intSlotB!==null&&intersectionPointB!==null){intersectionPointB.x=intXB;intersectionPointB.y=intYB;if(normalRadians!==null){normalRadians.y=intBN;}}return intSlotA;};Armature.prototype.getBone=function(name){for(var _i=0,_a=this._bones;_i<_a.length;_i++){var bone=_a[_i];if(bone.name===name){return bone;}}return null;};Armature.prototype.getBoneByDisplay=function(display){var slot=this.getSlotByDisplay(display);return slot!==null?slot.parent:null;};Armature.prototype.getSlot=function(name){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.name===name){return slot;}}return null;};Armature.prototype.getSlotByDisplay=function(display){if(display!==null){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.display===display){return slot;}}}return null;};Armature.prototype.getBones=function(){return this._bones;};Armature.prototype.getSlots=function(){return this._slots;};Object.defineProperty(Armature.prototype,"flipX",{get:function(){return this._flipX;},set:function(value){if(this._flipX===value){return;}this._flipX=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"flipY",{get:function(){return this._flipY;},set:function(value){if(this._flipY===value){return;}this._flipY=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"cacheFrameRate",{get:function(){return this._armatureData.cacheFrameRate;},set:function(value){if(this._armatureData.cacheFrameRate!==value){this._armatureData.cacheFrames(value);for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var childArmature=slot.childArmature;if(childArmature!==null){childArmature.cacheFrameRate=value;}}}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"name",{get:function(){return this._armatureData.name;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"armatureData",{get:function(){return this._armatureData;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"animation",{get:function(){return this._animation;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"proxy",{get:function(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"eventDispatcher",{get:function(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"display",{get:function(){return this._display;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"replacedTexture",{get:function(){return this._replacedTexture;},set:function(value){if(this._replacedTexture===value){return;}if(this._replaceTextureAtlasData!==null){this._replaceTextureAtlasData.returnToPool();this._replaceTextureAtlasData=null;}this._replacedTexture=value;for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];slot.invalidUpdate();slot.update(-1);}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"clock",{get:function(){return this._clock;},set:function(value){if(this._clock===value){return;}if(this._clock!==null){this._clock.remove(this);}this._clock=value;if(this._clock){this._clock.add(this);}for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var childArmature=slot.childArmature;if(childArmature!==null){childArmature.clock=this._clock;}}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"parent",{get:function(){return this._parent;},enumerable:true,configurable:true});Armature.prototype.replaceTexture=function(texture){this.replacedTexture=texture;};Armature.prototype.hasEventListener=function(type){return this._proxy.hasDBEventListener(type);};Armature.prototype.addEventListener=function(type,listener,target){this._proxy.addDBEventListener(type,listener,target);};Armature.prototype.removeEventListener=function(type,listener,target){this._proxy.removeDBEventListener(type,listener,target);};Armature.prototype.enableAnimationCache=function(frameRate){console.warn("Deprecated.");this.cacheFrameRate=frameRate;};Armature.prototype.getDisplay=function(){return this._display;};return Armature;}(dragonBones_1.BaseObject);dragonBones_1.Armature=Armature;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var TransformObject=function(_super){__extends(TransformObject,_super);function TransformObject(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.globalTransformMatrix=new dragonBones.Matrix();_this.global=new dragonBones.Transform();_this.offset=new dragonBones.Transform();return _this;}TransformObject.prototype._onClear=function(){this.globalTransformMatrix.identity();this.global.identity();this.offset.identity();this.origin=null;this.userData=null;this._globalDirty=false;this._armature=null;};TransformObject.prototype.updateGlobalTransform=function(){if(this._globalDirty){this._globalDirty=false;this.global.fromMatrix(this.globalTransformMatrix);}};Object.defineProperty(TransformObject.prototype,"armature",{get:function(){return this._armature;},enumerable:true,configurable:true});TransformObject._helpMatrix=new dragonBones.Matrix();TransformObject._helpTransform=new dragonBones.Transform();TransformObject._helpPoint=new dragonBones.Point();return TransformObject;}(dragonBones.BaseObject);dragonBones.TransformObject=TransformObject;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Bone=function(_super){__extends(Bone,_super);function Bone(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.animationPose=new dragonBones.Transform();_this._blendState=new dragonBones.BlendState();return _this;}Bone.toString=function(){return "[class dragonBones.Bone]";};Bone.prototype._onClear=function(){_super.prototype._onClear.call(this);this.offsetMode=1;this.animationPose.identity();this._transformDirty=false;this._childrenTransformDirty=false;this._localDirty=true;this._hasConstraint=false;this._visible=true;this._cachedFrameIndex=-1;this._blendState.clear();this._boneData=null;this._parent=null;this._cachedFrameIndices=null;};Bone.prototype._updateGlobalTransformMatrix=function(isCache){var boneData=this._boneData;var global=this.global;var globalTransformMatrix=this.globalTransformMatrix;var origin=this.origin;var offset=this.offset;var animationPose=this.animationPose;var parent=this._parent;var flipX=this._armature.flipX;var flipY=this._armature.flipY===dragonBones.DragonBones.yDown;var inherit=parent!==null;var rotation=0.0;if(this.offsetMode===1){if(origin!==null){global.x=origin.x+offset.x+animationPose.x;global.scaleX=origin.scaleX*offset.scaleX*animationPose.scaleX;global.scaleY=origin.scaleY*offset.scaleY*animationPose.scaleY;if(dragonBones.DragonBones.yDown){global.y=origin.y+offset.y+animationPose.y;global.skew=origin.skew+offset.skew+animationPose.skew;global.rotation=origin.rotation+offset.rotation+animationPose.rotation;}else {global.y=origin.y-offset.y+animationPose.y;global.skew=origin.skew-offset.skew+animationPose.skew;global.rotation=origin.rotation-offset.rotation+animationPose.rotation;}}else {global.copyFrom(offset);if(!dragonBones.DragonBones.yDown){global.y=-global.y;global.skew=-global.skew;global.rotation=-global.rotation;}global.add(animationPose);}}else if(this.offsetMode===0){if(origin!==null){global.copyFrom(origin).add(animationPose);}else {global.copyFrom(animationPose);}}else {inherit=false;global.copyFrom(offset);if(!dragonBones.DragonBones.yDown){global.y=-global.y;global.skew=-global.skew;global.rotation=-global.rotation;}}if(inherit){var parentMatrix=parent._boneData.type===0?parent.globalTransformMatrix:parent._getGlobalTransformMatrix(global.x,global.y);if(boneData.inheritScale){if(!boneData.inheritRotation){parent.updateGlobalTransform();if(flipX&&flipY){rotation=global.rotation-(parent.global.rotation+Math.PI);}else if(flipX){rotation=global.rotation+parent.global.rotation+Math.PI;}else if(flipY){rotation=global.rotation+parent.global.rotation;}else {rotation=global.rotation-parent.global.rotation;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);globalTransformMatrix.concat(parentMatrix);if(boneData.inheritTranslation){global.x=globalTransformMatrix.tx;global.y=globalTransformMatrix.ty;}else {globalTransformMatrix.tx=global.x;globalTransformMatrix.ty=global.y;}if(isCache){global.fromMatrix(globalTransformMatrix);}else {this._globalDirty=true;}}else {if(boneData.inheritTranslation){var x=global.x;var y=global.y;global.x=parentMatrix.a*x+parentMatrix.c*y+parentMatrix.tx;global.y=parentMatrix.b*x+parentMatrix.d*y+parentMatrix.ty;}else {if(flipX){global.x=-global.x;}if(flipY){global.y=-global.y;}}if(boneData.inheritRotation){parent.updateGlobalTransform();if(parent.global.scaleX<0.0){rotation=global.rotation+parent.global.rotation+Math.PI;}else {rotation=global.rotation+parent.global.rotation;}if(parentMatrix.a*parentMatrix.d-parentMatrix.b*parentMatrix.c<0.0){rotation-=global.rotation*2.0;if(flipX!==flipY||boneData.inheritReflection){global.skew+=Math.PI;}if(!dragonBones.DragonBones.yDown){global.skew=-global.skew;}}global.rotation=rotation;}else if(flipX||flipY){if(flipX&&flipY){rotation=global.rotation+Math.PI;}else {if(flipX){rotation=Math.PI-global.rotation;}else {rotation=-global.rotation;}global.skew+=Math.PI;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);}}else {if(flipX||flipY){if(flipX){global.x=-global.x;}if(flipY){global.y=-global.y;}if(flipX&&flipY){rotation=global.rotation+Math.PI;}else {if(flipX){rotation=Math.PI-global.rotation;}else {rotation=-global.rotation;}global.skew+=Math.PI;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);}};Bone.prototype.init=function(boneData,armatureValue){if(this._boneData!==null){return;}this._boneData=boneData;this._armature=armatureValue;if(this._boneData.parent!==null){this._parent=this._armature.getBone(this._boneData.parent.name);}this._armature._addBone(this);this.origin=this._boneData.transform;};Bone.prototype.update=function(cacheFrameIndex){this._blendState.dirty=false;if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else {if(this._hasConstraint){for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}}else {if(this._hasConstraint){for(var _b=0,_c=this._armature._constraints;_b<_c.length;_b++){var constraint=_c[_b];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}}if(this._transformDirty){this._transformDirty=false;this._childrenTransformDirty=true;if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;if(this._localDirty){this._updateGlobalTransformMatrix(isCache);}if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}}else if(this._childrenTransformDirty){this._childrenTransformDirty=false;}this._localDirty=true;};Bone.prototype.updateByConstraint=function(){if(this._localDirty){this._localDirty=false;if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._updateGlobalTransformMatrix(true);}this._transformDirty=true;}};Bone.prototype.invalidUpdate=function(){this._transformDirty=true;};Bone.prototype.contains=function(value){if(value===this){return false;}var ancestor=value;while(ancestor!==this&&ancestor!==null){ancestor=ancestor.parent;}return ancestor===this;};Object.defineProperty(Bone.prototype,"boneData",{get:function(){return this._boneData;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"visible",{get:function(){return this._visible;},set:function(value){if(this._visible===value){return;}this._visible=value;for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){slot._updateVisible();}}},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"name",{get:function(){return this._boneData.name;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"parent",{get:function(){return this._parent;},enumerable:true,configurable:true});Bone.prototype.getBones=function(){console.warn("Deprecated.");var bones=new Array();for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(bone.parent===this){bones.push(bone);}}return bones;};Bone.prototype.getSlots=function(){console.warn("Deprecated.");var slots=new Array();for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){slots.push(slot);}}return slots;};Object.defineProperty(Bone.prototype,"slot",{get:function(){console.warn("Deprecated.");for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){return slot;}}return null;},enumerable:true,configurable:true});return Bone;}(dragonBones.TransformObject);dragonBones.Bone=Bone;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Surface=function(_super){__extends(Surface,_super);function Surface(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._vertices=[];_this._deformVertices=[];_this._hullCache=[];_this._matrixCahce=[];return _this;}Surface.toString=function(){return "[class dragonBones.Surface]";};Surface.prototype._onClear=function(){_super.prototype._onClear.call(this);this._dX=0.0;this._dY=0.0;this._k=0.0;this._kX=0.0;this._kY=0.0;this._vertices.length=0;this._deformVertices.length=0;this._matrixCahce.length=0;this._hullCache.length=0;};Surface.prototype._getAffineTransform=function(x,y,lX,lY,aX,aY,bX,bY,cX,cY,transform,matrix,isDown){var dabX=bX-aX;var dabY=bY-aY;var dacX=cX-aX;var dacY=cY-aY;transform.rotation=Math.atan2(dabY,dabX);transform.skew=Math.atan2(dacY,dacX)-Math.PI*0.5-transform.rotation;if(isDown){transform.rotation+=Math.PI;}transform.scaleX=Math.sqrt(dabX*dabX+dabY*dabY)/lX;transform.scaleY=Math.sqrt(dacX*dacX+dacY*dacY)/lY;transform.toMatrix(matrix);transform.x=matrix.tx=aX-(matrix.a*x+matrix.c*y);transform.y=matrix.ty=aY-(matrix.b*x+matrix.d*y);};Surface.prototype._updateVertices=function(){var originalVertices=this._boneData.vertices;var vertices=this._vertices;var animationVertices=this._deformVertices;if(this._parent!==null){if(this._parent._boneData.type===1){for(var i=0,l=originalVertices.length;i<l;i+=2){var x=originalVertices[i]+animationVertices[i];var y=originalVertices[i+1]+animationVertices[i];var matrix=this._parent._getGlobalTransformMatrix(x,y);vertices[i]=matrix.a*x+matrix.c*y+matrix.tx;vertices[i+1]=matrix.b*x+matrix.d*y+matrix.ty;}}else {var parentMatrix=this._parent.globalTransformMatrix;for(var i=0,l=originalVertices.length;i<l;i+=2){var x=originalVertices[i]+animationVertices[i];var y=originalVertices[i+1]+animationVertices[i+1];vertices[i]=parentMatrix.a*x+parentMatrix.c*y+parentMatrix.tx;vertices[i+1]=parentMatrix.b*x+parentMatrix.d*y+parentMatrix.ty;}}}else {for(var i=0,l=originalVertices.length;i<l;i+=2){vertices[i]=originalVertices[i]+animationVertices[i];vertices[i+1]=originalVertices[i+1]+animationVertices[i+1];}}};Surface.prototype._updateGlobalTransformMatrix=function(isCache){var segmentXD=this._boneData.segmentX*2;var lastIndex=this._vertices.length-2;var lA=200.0;var raX=this._vertices[0];var raY=this._vertices[1];var rbX=this._vertices[segmentXD];var rbY=this._vertices[segmentXD+1];var rcX=this._vertices[lastIndex];var rcY=this._vertices[lastIndex+1];var rdX=this._vertices[lastIndex-segmentXD];var rdY=this._vertices[lastIndex-segmentXD+1];var dacX=raX+(rcX-raX)*0.5;var dacY=raY+(rcY-raY)*0.5;var dbdX=rbX+(rdX-rbX)*0.5;var dbdY=rbY+(rdY-rbY)*0.5;var aX=dacX+(dbdX-dacX)*0.5;var aY=dacY+(dbdY-dacY)*0.5;var bX=rbX+(rcX-rbX)*0.5;var bY=rbY+(rcY-rbY)*0.5;var cX=rdX+(rcX-rdX)*0.5;var cY=rdY+(rcY-rdY)*0.5;this._globalDirty=false;this._getAffineTransform(0.0,0.0,lA,lA,aX,aY,bX,bY,cX,cY,this.global,this.globalTransformMatrix,false);};Surface.prototype._getGlobalTransformMatrix=function(x,y){var lB=1000.0;if(x<-lB||lB<x||y<-lB||lB<y){return this.globalTransformMatrix;}var isDown=false;var lA=200.0;var surfaceData=this._boneData;var segmentX=surfaceData.segmentX;var segmentY=surfaceData.segmentY;var segmentXD=surfaceData.segmentX*2;var dX=this._dX;var dY=this._dY;var indexX=Math.floor((x+lA)/dX);var indexY=Math.floor((y+lA)/dY);var matrixIndex=0;var pX=indexX*dX-lA;var pY=indexY*dY-lA;var matrices=this._matrixCahce;var helpMatrix=Surface._helpMatrix;if(x<-lA){if(y<-lA||y>=lA){return this.globalTransformMatrix;}isDown=y>this._kX*(x+lA)+pY;matrixIndex=((segmentX*(segmentY+1)+segmentX*2+segmentY+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexY*(segmentXD+2);var ddX=this._hullCache[4];var ddY=this._hullCache[5];var sX=this._hullCache[2]-(segmentY-indexY)*ddX;var sY=this._hullCache[3]-(segmentY-indexY)*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(-lA,pY+dY,lB-lA,dY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],sX+ddX,sY+ddY,vertices[vertexIndex],vertices[vertexIndex+1],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(-lB,pY,lB-lA,dY,sX,sY,vertices[vertexIndex],vertices[vertexIndex+1],sX+ddX,sY+ddY,Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(x>=lA){if(y<-lA||y>=lA){return this.globalTransformMatrix;}isDown=y>this._kX*(x-lB)+pY;matrixIndex=((segmentX*(segmentY+1)+segmentX+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=(indexY+1)*(segmentXD+2)-2;var ddX=this._hullCache[4];var ddY=this._hullCache[5];var sX=this._hullCache[0]+indexY*ddX;var sY=this._hullCache[1]+indexY*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(lB,pY+dY,lB-lA,dY,sX+ddX,sY+ddY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],sX,sY,Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(lA,pY,lB-lA,dY,vertices[vertexIndex],vertices[vertexIndex+1],sX,sY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(y<-lA){if(x<-lA||x>=lA){return this.globalTransformMatrix;}isDown=y>this._kY*(x-pX-dX)-lB;matrixIndex=(segmentX*(segmentY+1)+indexX*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexX*2;var ddX=this._hullCache[10];var ddY=this._hullCache[11];var sX=this._hullCache[8]+indexX*ddX;var sY=this._hullCache[9]+indexX*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,-lA,dX,lB-lA,vertices[vertexIndex+2],vertices[vertexIndex+3],vertices[vertexIndex],vertices[vertexIndex+1],sX+ddX,sY+ddY,Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,-lB,dX,lB-lA,sX,sY,sX+ddX,sY+ddY,vertices[vertexIndex],vertices[vertexIndex+1],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(y>=lA){if(x<-lA||x>=lA){return this.globalTransformMatrix;}isDown=y>this._kY*(x-pX-dX)+lA;matrixIndex=((segmentX*(segmentY+1)+segmentX+segmentY+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=segmentY*(segmentXD+2)+indexX*2;var ddX=this._hullCache[10];var ddY=this._hullCache[11];var sX=this._hullCache[6]-(segmentX-indexX)*ddX;var sY=this._hullCache[7]-(segmentX-indexX)*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,lB,dX,lB-lA,sX+ddX,sY+ddY,sX,sY,vertices[vertexIndex+2],vertices[vertexIndex+3],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,lA,dX,lB-lA,vertices[vertexIndex],vertices[vertexIndex+1],vertices[vertexIndex+2],vertices[vertexIndex+3],sX,sY,Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else {isDown=y>this._k*(x-pX-dX)+pY;matrixIndex=((segmentX*indexY+indexX)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexX*2+indexY*(segmentXD+2);var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,pY+dY,dX,dY,vertices[vertexIndex+segmentXD+4],vertices[vertexIndex+segmentXD+5],vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],vertices[vertexIndex+2],vertices[vertexIndex+3],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,pY,dX,dY,vertices[vertexIndex],vertices[vertexIndex+1],vertices[vertexIndex+2],vertices[vertexIndex+3],vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}return helpMatrix;};Surface.prototype.init=function(surfaceData,armatureValue){if(this._boneData!==null){return;}_super.prototype.init.call(this,surfaceData,armatureValue);var segmentX=surfaceData.segmentX;var segmentY=surfaceData.segmentY;var vertexCount=surfaceData.vertices.length;var lB=1000.0;var lA=200.0;this._dX=lA*2.0/segmentX;this._dY=lA*2.0/segmentY;this._k=-this._dY/this._dX;this._kX=-this._dY/(lB-lA);this._kY=-(lB-lA)/this._dX;this._vertices.length=vertexCount;this._deformVertices.length=vertexCount;this._matrixCahce.length=(segmentX*segmentY+segmentX*2+segmentY*2)*2*7;this._hullCache.length=10;for(var i=0;i<vertexCount;++i){this._deformVertices[i]=0.0;}};Surface.prototype.update=function(cacheFrameIndex){this._blendState.dirty=false;if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else {if(this._hasConstraint){for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}}else {if(this._hasConstraint){for(var _b=0,_c=this._armature._constraints;_b<_c.length;_b++){var constraint=_c[_b];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}}if(this._transformDirty){this._transformDirty=false;this._childrenTransformDirty=true;for(var i=0,l=this._matrixCahce.length;i<l;i+=7){this._matrixCahce[i]=-1.0;}this._updateVertices();if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;if(this._localDirty){this._updateGlobalTransformMatrix(isCache);}if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}var lB=1000.0;var lA=200.0;var ddX=2*this.global.x;var ddY=2*this.global.y;var helpPoint=Surface._helpPoint;this.globalTransformMatrix.transformPoint(lB,-lA,helpPoint);this._hullCache[0]=helpPoint.x;this._hullCache[1]=helpPoint.y;this._hullCache[2]=ddX-helpPoint.x;this._hullCache[3]=ddY-helpPoint.y;this.globalTransformMatrix.transformPoint(0.0,this._dY,helpPoint,true);this._hullCache[4]=helpPoint.x;this._hullCache[5]=helpPoint.y;this.globalTransformMatrix.transformPoint(lA,lB,helpPoint);this._hullCache[6]=helpPoint.x;this._hullCache[7]=helpPoint.y;this._hullCache[8]=ddX-helpPoint.x;this._hullCache[9]=ddY-helpPoint.y;this.globalTransformMatrix.transformPoint(this._dX,0.0,helpPoint,true);this._hullCache[10]=helpPoint.x;this._hullCache[11]=helpPoint.y;}else if(this._childrenTransformDirty){this._childrenTransformDirty=false;}this._localDirty=true;};return Surface;}(dragonBones.Bone);dragonBones.Surface=Surface;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Slot=function(_super){__extends(Slot,_super);function Slot(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._localMatrix=new dragonBones.Matrix();_this._colorTransform=new dragonBones.ColorTransform();_this._displayDatas=[];_this._displayList=[];_this._deformVertices=null;_this._rawDisplay=null;_this._meshDisplay=null;return _this;}Slot.prototype._onClear=function(){_super.prototype._onClear.call(this);var disposeDisplayList=[];for(var _i=0,_a=this._displayList;_i<_a.length;_i++){var eachDisplay=_a[_i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&disposeDisplayList.indexOf(eachDisplay)<0){disposeDisplayList.push(eachDisplay);}}for(var _b=0,disposeDisplayList_1=disposeDisplayList;_b<disposeDisplayList_1.length;_b++){var eachDisplay=disposeDisplayList_1[_b];if(eachDisplay instanceof dragonBones.Armature){eachDisplay.dispose();}else {this._disposeDisplay(eachDisplay,true);}}if(this._deformVertices!==null){this._deformVertices.returnToPool();}if(this._meshDisplay!==null&&this._meshDisplay!==this._rawDisplay){this._disposeDisplay(this._meshDisplay,false);}if(this._rawDisplay!==null){this._disposeDisplay(this._rawDisplay,false);}this.displayController=null;this._displayDirty=false;this._zOrderDirty=false;this._blendModeDirty=false;this._colorDirty=false;this._transformDirty=false;this._visible=true;this._blendMode=0;this._displayIndex=-1;this._animationDisplayIndex=-1;this._zOrder=0;this._cachedFrameIndex=-1;this._pivotX=0.0;this._pivotY=0.0;this._localMatrix.identity();this._colorTransform.identity();this._displayList.length=0;this._displayDatas.length=0;this._slotData=null;this._rawDisplayDatas=null;this._displayData=null;this._boundingBoxData=null;this._textureData=null;this._deformVertices=null;this._rawDisplay=null;this._meshDisplay=null;this._display=null;this._childArmature=null;this._parent=null;this._cachedFrameIndices=null;};Slot.prototype._getDefaultRawDisplayData=function(displayIndex){var defaultSkin=this._armature._armatureData.defaultSkin;if(defaultSkin!==null){var defaultRawDisplayDatas=defaultSkin.getDisplays(this._slotData.name);if(defaultRawDisplayDatas!==null){return displayIndex<defaultRawDisplayDatas.length?defaultRawDisplayDatas[displayIndex]:null;}}return null;};Slot.prototype._updateDisplayData=function(){var prevDisplayData=this._displayData;var prevVerticesData=this._deformVertices!==null?this._deformVertices.verticesData:null;var prevTextureData=this._textureData;var rawDisplayData=null;var currentVerticesData=null;this._displayData=null;this._boundingBoxData=null;this._textureData=null;if(this._displayIndex>=0){if(this._rawDisplayDatas!==null){rawDisplayData=this._displayIndex<this._rawDisplayDatas.length?this._rawDisplayDatas[this._displayIndex]:null;}if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(this._displayIndex);}if(this._displayIndex<this._displayDatas.length){this._displayData=this._displayDatas[this._displayIndex];}}if(this._displayData!==null){if(this._displayData.type===2){currentVerticesData=this._displayData.vertices;}else if(this._displayData.type===4){currentVerticesData=this._displayData.vertices;}else if(rawDisplayData!==null){if(rawDisplayData.type===2){currentVerticesData=rawDisplayData.vertices;}else if(rawDisplayData.type===4){currentVerticesData=rawDisplayData.vertices;}}if(this._displayData.type===3){this._boundingBoxData=this._displayData.boundingBox;}else if(rawDisplayData!==null){if(rawDisplayData.type===3){this._boundingBoxData=rawDisplayData.boundingBox;}}if(this._displayData.type===0){this._textureData=this._displayData.texture;}else if(this._displayData.type===2){this._textureData=this._displayData.texture;}}if(this._displayData!==prevDisplayData||currentVerticesData!==prevVerticesData||this._textureData!==prevTextureData){if(currentVerticesData===null&&this._textureData!==null){var imageDisplayData=this._displayData;var scale=this._textureData.parent.scale*this._armature._armatureData.scale;var frame=this._textureData.frame;this._pivotX=imageDisplayData.pivot.x;this._pivotY=imageDisplayData.pivot.y;var rect=frame!==null?frame:this._textureData.region;var width=rect.width;var height=rect.height;if(this._textureData.rotated&&frame===null){width=rect.height;height=rect.width;}this._pivotX*=width*scale;this._pivotY*=height*scale;if(frame!==null){this._pivotX+=frame.x*scale;this._pivotY+=frame.y*scale;}if(this._displayData!==null&&rawDisplayData!==null&&this._displayData!==rawDisplayData){rawDisplayData.transform.toMatrix(Slot._helpMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(0.0,0.0,Slot._helpPoint);this._pivotX-=Slot._helpPoint.x;this._pivotY-=Slot._helpPoint.y;this._displayData.transform.toMatrix(Slot._helpMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(0.0,0.0,Slot._helpPoint);this._pivotX+=Slot._helpPoint.x;this._pivotY+=Slot._helpPoint.y;}if(!dragonBones.DragonBones.yDown){this._pivotY=(this._textureData.rotated?this._textureData.region.width:this._textureData.region.height)*scale-this._pivotY;}}else {this._pivotX=0.0;this._pivotY=0.0;}if(rawDisplayData!==null){this.origin=rawDisplayData.transform;}else if(this._displayData!==null){this.origin=this._displayData.transform;}else {this.origin=null;}if(currentVerticesData!==prevVerticesData){if(this._deformVertices===null){this._deformVertices=dragonBones.BaseObject.borrowObject(dragonBones.DeformVertices);}this._deformVertices.init(currentVerticesData,this._armature);}else if(this._deformVertices!==null&&this._textureData!==prevTextureData){this._deformVertices.verticesDirty=true;}this._displayDirty=true;this._transformDirty=true;}};Slot.prototype._updateDisplay=function(){var prevDisplay=this._display!==null?this._display:this._rawDisplay;var prevChildArmature=this._childArmature;if(this._displayIndex>=0&&this._displayIndex<this._displayList.length){this._display=this._displayList[this._displayIndex];if(this._display!==null&&this._display instanceof dragonBones.Armature){this._childArmature=this._display;this._display=this._childArmature.display;}else {this._childArmature=null;}}else {this._display=null;this._childArmature=null;}var currentDisplay=this._display!==null?this._display:this._rawDisplay;if(currentDisplay!==prevDisplay){this._onUpdateDisplay();this._replaceDisplay(prevDisplay);this._transformDirty=true;this._visibleDirty=true;this._blendModeDirty=true;this._colorDirty=true;}if(currentDisplay===this._rawDisplay||currentDisplay===this._meshDisplay){this._updateFrame();}if(this._childArmature!==prevChildArmature){if(prevChildArmature!==null){prevChildArmature._parent=null;prevChildArmature.clock=null;if(prevChildArmature.inheritAnimation){prevChildArmature.animation.reset();}}if(this._childArmature!==null){this._childArmature._parent=this;this._childArmature.clock=this._armature.clock;if(this._childArmature.inheritAnimation){if(this._childArmature.cacheFrameRate===0){var cacheFrameRate=this._armature.cacheFrameRate;if(cacheFrameRate!==0){this._childArmature.cacheFrameRate=cacheFrameRate;}}var actions=null;if(this._displayData!==null&&this._displayData.type===1){actions=this._displayData.actions;}else if(this._displayIndex>=0&&this._rawDisplayDatas!==null){var rawDisplayData=this._displayIndex<this._rawDisplayDatas.length?this._rawDisplayDatas[this._displayIndex]:null;if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(this._displayIndex);}if(rawDisplayData!==null&&rawDisplayData.type===1){actions=rawDisplayData.actions;}}if(actions!==null&&actions.length>0){for(var _i=0,actions_1=actions;_i<actions_1.length;_i++){var action=actions_1[_i];var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);eventObject.slot=this;this._armature._bufferAction(eventObject,false);}}else {this._childArmature.animation.play();}}}}};Slot.prototype._updateGlobalTransformMatrix=function(isCache){var parentMatrix=this._parent._boneData.type===0?this._parent.globalTransformMatrix:this._parent._getGlobalTransformMatrix(this.global.x,this.global.y);this.globalTransformMatrix.copyFrom(this._localMatrix);this.globalTransformMatrix.concat(parentMatrix);if(isCache){this.global.fromMatrix(this.globalTransformMatrix);}else {this._globalDirty=true;}};Slot.prototype._setDisplayIndex=function(value,isAnimation){if(isAnimation===void 0){isAnimation=false;}if(isAnimation){if(this._animationDisplayIndex===value){return false;}this._animationDisplayIndex=value;}if(this._displayIndex===value){return false;}this._displayIndex=value;this._displayDirty=true;this._updateDisplayData();return this._displayDirty;};Slot.prototype._setZorder=function(value){if(this._zOrder===value);this._zOrder=value;this._zOrderDirty=true;return this._zOrderDirty;};Slot.prototype._setColor=function(value){this._colorTransform.copyFrom(value);this._colorDirty=true;return this._colorDirty;};Slot.prototype._setDisplayList=function(value){if(value!==null&&value.length>0){if(this._displayList.length!==value.length){this._displayList.length=value.length;}for(var i=0,l=value.length;i<l;++i){var eachDisplay=value[i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&!(eachDisplay instanceof dragonBones.Armature)&&this._displayList.indexOf(eachDisplay)<0){this._initDisplay(eachDisplay,true);}this._displayList[i]=eachDisplay;}}else if(this._displayList.length>0){this._displayList.length=0;}if(this._displayIndex>=0&&this._displayIndex<this._displayList.length){this._displayDirty=this._display!==this._displayList[this._displayIndex];}else {this._displayDirty=this._display!==null;}this._updateDisplayData();return this._displayDirty;};Slot.prototype.init=function(slotData,armatureValue,rawDisplay,meshDisplay){if(this._slotData!==null){return;}this._slotData=slotData;this._isFromCache=false;this._visibleDirty=true;this._blendModeDirty=true;this._colorDirty=true;this._blendMode=this._slotData.blendMode;this._zOrder=this._slotData.zOrder;this._colorTransform.copyFrom(this._slotData.color);this._rawDisplay=rawDisplay;this._meshDisplay=meshDisplay;this._armature=armatureValue;var slotParent=this._armature.getBone(this._slotData.parent.name);if(slotParent!==null){this._parent=slotParent;}this._armature._addSlot(this);this._initDisplay(this._rawDisplay,false);if(this._rawDisplay!==this._meshDisplay){this._initDisplay(this._meshDisplay,false);}this._onUpdateDisplay();this._addDisplay();};Slot.prototype.update=function(cacheFrameIndex){this._isFromCache=false;if(this._displayDirty){this._displayDirty=false;this._updateDisplay();if(this._transformDirty){if(this.origin!==null){this.global.copyFrom(this.origin).add(this.offset).toMatrix(this._localMatrix);}else {this.global.copyFrom(this.offset).toMatrix(this._localMatrix);}}}if(this._zOrderDirty){this._zOrderDirty=false;this._updateZOrder();}if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else if(this._transformDirty||this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}else if(this._transformDirty||this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}if(this._display===null){return;}if(this._visibleDirty){this._visibleDirty=false;this._updateVisible();}if(this._blendModeDirty){this._blendModeDirty=false;this._updateBlendMode();}if(this._colorDirty){this._colorDirty=false;this._updateColor();}if(this._deformVertices!==null&&this._deformVertices.verticesData!==null&&this._display===this._meshDisplay){var isSkinned=this._deformVertices.verticesData.weight!==null;var isSurface=this._parent._boneData.type!==0;if(this._deformVertices.verticesDirty||isSkinned&&this._deformVertices.isBonesUpdate()||isSurface&&this._parent._childrenTransformDirty){this._deformVertices.verticesDirty=false;this._updateMesh();}if(isSkinned||isSurface){return;}}if(this._transformDirty){this._transformDirty=false;if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;this._updateGlobalTransformMatrix(isCache);if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._isFromCache=true;this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}this._updateTransform();}};Slot.prototype.updateTransformAndMatrix=function(){if(this._transformDirty){this._transformDirty=false;this._updateGlobalTransformMatrix(false);}};Slot.prototype.replaceDisplayData=function(value,displayIndex){if(displayIndex===void 0){displayIndex=-1;}if(displayIndex<0){if(this._displayIndex<0){displayIndex=0;}else {displayIndex=this._displayIndex;}}if(this._displayDatas.length<=displayIndex){this._displayDatas.length=displayIndex+1;for(var i=0,l=this._displayDatas.length;i<l;++i){if(!this._displayDatas[i]){this._displayDatas[i]=null;}}}this._displayDatas[displayIndex]=value;};Slot.prototype.containsPoint=function(x,y){if(this._boundingBoxData===null){return false;}this.updateTransformAndMatrix();Slot._helpMatrix.copyFrom(this.globalTransformMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(x,y,Slot._helpPoint);return this._boundingBoxData.containsPoint(Slot._helpPoint.x,Slot._helpPoint.y);};Slot.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}if(this._boundingBoxData===null){return 0;}this.updateTransformAndMatrix();Slot._helpMatrix.copyFrom(this.globalTransformMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(xA,yA,Slot._helpPoint);xA=Slot._helpPoint.x;yA=Slot._helpPoint.y;Slot._helpMatrix.transformPoint(xB,yB,Slot._helpPoint);xB=Slot._helpPoint.x;yB=Slot._helpPoint.y;var intersectionCount=this._boundingBoxData.intersectsSegment(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians);if(intersectionCount>0){if(intersectionCount===1||intersectionCount===2){if(intersectionPointA!==null){this.globalTransformMatrix.transformPoint(intersectionPointA.x,intersectionPointA.y,intersectionPointA);if(intersectionPointB!==null){intersectionPointB.x=intersectionPointA.x;intersectionPointB.y=intersectionPointA.y;}}else if(intersectionPointB!==null){this.globalTransformMatrix.transformPoint(intersectionPointB.x,intersectionPointB.y,intersectionPointB);}}else {if(intersectionPointA!==null){this.globalTransformMatrix.transformPoint(intersectionPointA.x,intersectionPointA.y,intersectionPointA);}if(intersectionPointB!==null){this.globalTransformMatrix.transformPoint(intersectionPointB.x,intersectionPointB.y,intersectionPointB);}}if(normalRadians!==null){this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.x),Math.sin(normalRadians.x),Slot._helpPoint,true);normalRadians.x=Math.atan2(Slot._helpPoint.y,Slot._helpPoint.x);this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.y),Math.sin(normalRadians.y),Slot._helpPoint,true);normalRadians.y=Math.atan2(Slot._helpPoint.y,Slot._helpPoint.x);}}return intersectionCount;};Slot.prototype.invalidUpdate=function(){this._displayDirty=true;this._transformDirty=true;};Object.defineProperty(Slot.prototype,"visible",{get:function(){return this._visible;},set:function(value){if(this._visible===value){return;}this._visible=value;this._updateVisible();},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayIndex",{get:function(){return this._displayIndex;},set:function(value){if(this._setDisplayIndex(value)){this.update(-1);}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"name",{get:function(){return this._slotData.name;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayList",{get:function(){return this._displayList.concat();},set:function(value){var backupDisplayList=this._displayList.concat();var disposeDisplayList=new Array();if(this._setDisplayList(value)){this.update(-1);}for(var _i=0,backupDisplayList_1=backupDisplayList;_i<backupDisplayList_1.length;_i++){var eachDisplay=backupDisplayList_1[_i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&this._displayList.indexOf(eachDisplay)<0&&disposeDisplayList.indexOf(eachDisplay)<0){disposeDisplayList.push(eachDisplay);}}for(var _a=0,disposeDisplayList_2=disposeDisplayList;_a<disposeDisplayList_2.length;_a++){var eachDisplay=disposeDisplayList_2[_a];if(eachDisplay instanceof dragonBones.Armature);else {this._disposeDisplay(eachDisplay,true);}}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"slotData",{get:function(){return this._slotData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplayDatas",{get:function(){return this._rawDisplayDatas;},set:function(value){if(this._rawDisplayDatas===value){return;}this._displayDirty=true;this._rawDisplayDatas=value;if(this._rawDisplayDatas!==null){this._displayDatas.length=this._rawDisplayDatas.length;for(var i=0,l=this._displayDatas.length;i<l;++i){var rawDisplayData=this._rawDisplayDatas[i];if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(i);}this._displayDatas[i]=rawDisplayData;}}else {this._displayDatas.length=0;}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayData",{get:function(){return this._displayData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"boundingBoxData",{get:function(){return this._boundingBoxData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplay",{get:function(){return this._rawDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"meshDisplay",{get:function(){return this._meshDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"display",{get:function(){return this._display;},set:function(value){if(this._display===value){return;}var displayListLength=this._displayList.length;if(this._displayIndex<0&&displayListLength===0){this._displayIndex=0;}if(this._displayIndex<0){return;}else {var replaceDisplayList=this.displayList;if(displayListLength<=this._displayIndex){replaceDisplayList.length=this._displayIndex+1;}replaceDisplayList[this._displayIndex]=value;this.displayList=replaceDisplayList;}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"childArmature",{get:function(){return this._childArmature;},set:function(value){if(this._childArmature===value){return;}this.display=value;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"parent",{get:function(){return this._parent;},enumerable:true,configurable:true});Slot.prototype.getDisplay=function(){return this._display;};Slot.prototype.setDisplay=function(value){this.display=value;};return Slot;}(dragonBones.TransformObject);dragonBones.Slot=Slot;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Constraint=function(_super){__extends(Constraint,_super);function Constraint(){return _super!==null&&_super.apply(this,arguments)||this;}Constraint.prototype._onClear=function(){this._armature=null;this._target=null;this._root=null;this._bone=null;};Object.defineProperty(Constraint.prototype,"name",{get:function(){return this._constraintData.name;},enumerable:true,configurable:true});Constraint._helpMatrix=new dragonBones.Matrix();Constraint._helpTransform=new dragonBones.Transform();Constraint._helpPoint=new dragonBones.Point();return Constraint;}(dragonBones.BaseObject);dragonBones.Constraint=Constraint;var IKConstraint=function(_super){__extends(IKConstraint,_super);function IKConstraint(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraint.toString=function(){return "[class dragonBones.IKConstraint]";};IKConstraint.prototype._onClear=function(){_super.prototype._onClear.call(this);this._scaleEnabled=false;this._bendPositive=false;this._weight=1.0;this._constraintData=null;};IKConstraint.prototype._computeA=function(){var ikGlobal=this._target.global;var global=this._root.global;var globalTransformMatrix=this._root.globalTransformMatrix;var radian=Math.atan2(ikGlobal.y-global.y,ikGlobal.x-global.x);if(global.scaleX<0.0){radian+=Math.PI;}global.rotation+=dragonBones.Transform.normalizeRadian(radian-global.rotation)*this._weight;global.toMatrix(globalTransformMatrix);};IKConstraint.prototype._computeB=function(){var boneLength=this._bone._boneData.length;var parent=this._root;var ikGlobal=this._target.global;var parentGlobal=parent.global;var global=this._bone.global;var globalTransformMatrix=this._bone.globalTransformMatrix;var x=globalTransformMatrix.a*boneLength;var y=globalTransformMatrix.b*boneLength;var lLL=x*x+y*y;var lL=Math.sqrt(lLL);var dX=global.x-parentGlobal.x;var dY=global.y-parentGlobal.y;var lPP=dX*dX+dY*dY;var lP=Math.sqrt(lPP);var rawRadian=global.rotation;var rawParentRadian=parentGlobal.rotation;var rawRadianA=Math.atan2(dY,dX);dX=ikGlobal.x-parentGlobal.x;dY=ikGlobal.y-parentGlobal.y;var lTT=dX*dX+dY*dY;var lT=Math.sqrt(lTT);var radianA=0.0;if(lL+lP<=lT||lT+lL<=lP||lT+lP<=lL){radianA=Math.atan2(ikGlobal.y-parentGlobal.y,ikGlobal.x-parentGlobal.x);if(lL+lP<=lT);else if(lP<lL){radianA+=Math.PI;}}else {var h=(lPP-lLL+lTT)/(2.0*lTT);var r=Math.sqrt(lPP-h*h*lTT)/lT;var hX=parentGlobal.x+dX*h;var hY=parentGlobal.y+dY*h;var rX=-dY*r;var rY=dX*r;var isPPR=false;var parentParent=parent.parent;if(parentParent!==null){var parentParentMatrix=parentParent.globalTransformMatrix;isPPR=parentParentMatrix.a*parentParentMatrix.d-parentParentMatrix.b*parentParentMatrix.c<0.0;}if(isPPR!==this._bendPositive){global.x=hX-rX;global.y=hY-rY;}else {global.x=hX+rX;global.y=hY+rY;}radianA=Math.atan2(global.y-parentGlobal.y,global.x-parentGlobal.x);}var dR=dragonBones.Transform.normalizeRadian(radianA-rawRadianA);parentGlobal.rotation=rawParentRadian+dR*this._weight;parentGlobal.toMatrix(parent.globalTransformMatrix);var currentRadianA=rawRadianA+dR*this._weight;global.x=parentGlobal.x+Math.cos(currentRadianA)*lP;global.y=parentGlobal.y+Math.sin(currentRadianA)*lP;var radianB=Math.atan2(ikGlobal.y-global.y,ikGlobal.x-global.x);if(global.scaleX<0.0){radianB+=Math.PI;}global.rotation=parentGlobal.rotation+rawRadian-rawParentRadian+dragonBones.Transform.normalizeRadian(radianB-dR-rawRadian)*this._weight;global.toMatrix(globalTransformMatrix);};IKConstraint.prototype.init=function(constraintData,armature){if(this._constraintData!==null){return;}this._constraintData=constraintData;this._armature=armature;this._target=this._armature.getBone(this._constraintData.target.name);this._root=this._armature.getBone(this._constraintData.root.name);this._bone=this._constraintData.bone!==null?this._armature.getBone(this._constraintData.bone.name):null;{var ikConstraintData=this._constraintData;this._scaleEnabled=ikConstraintData.scaleEnabled;this._bendPositive=ikConstraintData.bendPositive;this._weight=ikConstraintData.weight;}this._root._hasConstraint=true;};IKConstraint.prototype.update=function(){this._root.updateByConstraint();if(this._bone!==null){this._bone.updateByConstraint();this._computeB();}else {this._computeA();}};IKConstraint.prototype.invalidUpdate=function(){this._root.invalidUpdate();if(this._bone!==null){this._bone.invalidUpdate();}};return IKConstraint;}(Constraint);dragonBones.IKConstraint=IKConstraint;var PathConstraint=function(_super){__extends(PathConstraint,_super);function PathConstraint(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._bones=[];_this._spaces=[];_this._positions=[];_this._curves=[];_this._boneLengths=[];_this._pathGlobalVertices=[];_this._segments=[10];return _this;}PathConstraint.toString=function(){return "[class dragonBones.PathConstraint]";};PathConstraint.prototype._onClear=function(){_super.prototype._onClear.call(this);this.dirty=false;this.pathOffset=0;this.position=0.0;this.spacing=0.0;this.rotateOffset=0.0;this.rotateMix=1.0;this.translateMix=1.0;this._pathSlot=null;this._bones.length=0;this._spaces.length=0;this._positions.length=0;this._curves.length=0;this._boneLengths.length=0;this._pathGlobalVertices.length=0;};PathConstraint.prototype._updatePathVertices=function(verticesData){var armature=this._armature;var dragonBonesData=armature.armatureData.parent;var scale=armature.armatureData.scale;var intArray=dragonBonesData.intArray;var floatArray=dragonBonesData.floatArray;var pathOffset=verticesData.offset;var pathVertexCount=intArray[pathOffset+0];var pathVertexOffset=intArray[pathOffset+2];this._pathGlobalVertices.length=pathVertexCount*2;var weightData=verticesData.weight;if(weightData===null){var parentBone=this._pathSlot.parent;parentBone.updateByConstraint();var matrix=parentBone.globalTransformMatrix;for(var i=0,iV_1=pathVertexOffset;i<pathVertexCount;i+=2){var vx=floatArray[iV_1++]*scale;var vy=floatArray[iV_1++]*scale;var x=matrix.a*vx+matrix.c*vy+matrix.tx;var y=matrix.b*vx+matrix.d*vy+matrix.ty;this._pathGlobalVertices[i]=x;this._pathGlobalVertices[i+1]=y;}return;}var bones=this._pathSlot._deformVertices.bones;var weightBoneCount=weightData.bones.length;var weightOffset=weightData.offset;var floatOffset=intArray[weightOffset+1];var iV=floatOffset;var iB=weightOffset+2+weightBoneCount;for(var i=0,iW=0;i<pathVertexCount;i++){var vertexBoneCount=intArray[iB++];var xG=0.0,yG=0.0;for(var ii=0,ll=vertexBoneCount;ii<ll;ii++){var boneIndex=intArray[iB++];var bone=bones[boneIndex];if(bone===null){continue;}bone.updateByConstraint();var matrix=bone.globalTransformMatrix;var weight=floatArray[iV++];var vx=floatArray[iV++]*scale;var vy=floatArray[iV++]*scale;xG+=(matrix.a*vx+matrix.c*vy+matrix.tx)*weight;yG+=(matrix.b*vx+matrix.d*vy+matrix.ty)*weight;}this._pathGlobalVertices[iW++]=xG;this._pathGlobalVertices[iW++]=yG;}};PathConstraint.prototype._computeVertices=function(start,count,offset,out){for(var i=offset,iW=start;i<count;i+=2){out[i]=this._pathGlobalVertices[iW++];out[i+1]=this._pathGlobalVertices[iW++];}};PathConstraint.prototype._computeBezierCurve=function(pathDisplayDta,spaceCount,tangents,percentPosition,percentSpacing){var armature=this._armature;var intArray=armature.armatureData.parent.intArray;var vertexCount=intArray[pathDisplayDta.vertices.offset+0];var positions=this._positions;var spaces=this._spaces;var isClosed=pathDisplayDta.closed;var curveVertices=Array();var verticesLength=vertexCount*2;var curveCount=verticesLength/6;var preCurve=-1;var position=this.position;positions.length=spaceCount*3+2;var pathLength=0.0;if(!pathDisplayDta.constantSpeed){var lenghts=pathDisplayDta.curveLengths;curveCount-=isClosed?1:2;pathLength=lenghts[curveCount];if(percentPosition){position*=pathLength;}if(percentSpacing){for(var i=0;i<spaceCount;i++){spaces[i]*=pathLength;}}curveVertices.length=8;for(var i=0,o=0,curve=0;i<spaceCount;i++,o+=3){var space=spaces[i];position+=space;if(isClosed){position%=pathLength;if(position<0){position+=pathLength;}curve=0;}else if(position<0){continue;}else if(position>pathLength){continue;}var percent=0.0;for(;;curve++){var len=lenghts[curve];if(position>len){continue;}if(curve===0){percent=position/len;}else {var preLen=lenghts[curve-1];percent=(position-preLen)/(len-preLen);}break;}if(curve!==preCurve){preCurve=curve;if(isClosed&&curve===curveCount){this._computeVertices(verticesLength-4,4,0,curveVertices);this._computeVertices(0,4,4,curveVertices);}else {this._computeVertices(curve*6+2,8,0,curveVertices);}}this.addCurvePosition(percent,curveVertices[0],curveVertices[1],curveVertices[2],curveVertices[3],curveVertices[4],curveVertices[5],curveVertices[6],curveVertices[7],positions,o,tangents);}return;}if(isClosed){verticesLength+=2;curveVertices.length=vertexCount;this._computeVertices(2,verticesLength-4,0,curveVertices);this._computeVertices(0,2,verticesLength-4,curveVertices);curveVertices[verticesLength-2]=curveVertices[0];curveVertices[verticesLength-1]=curveVertices[1];}else {curveCount--;verticesLength-=4;curveVertices.length=verticesLength;this._computeVertices(2,verticesLength,0,curveVertices);}var curves=new Array(curveCount);pathLength=0;var x1=curveVertices[0],y1=curveVertices[1],cx1=0,cy1=0,cx2=0,cy2=0,x2=0,y2=0;var tmpx,tmpy,dddfx,dddfy,ddfx,ddfy,dfx,dfy;for(var i=0,w=2;i<curveCount;i++,w+=6){cx1=curveVertices[w];cy1=curveVertices[w+1];cx2=curveVertices[w+2];cy2=curveVertices[w+3];x2=curveVertices[w+4];y2=curveVertices[w+5];tmpx=(x1-cx1*2+cx2)*0.1875;tmpy=(y1-cy1*2+cy2)*0.1875;dddfx=((cx1-cx2)*3-x1+x2)*0.09375;dddfy=((cy1-cy2)*3-y1+y2)*0.09375;ddfx=tmpx*2+dddfx;ddfy=tmpy*2+dddfy;dfx=(cx1-x1)*0.75+tmpx+dddfx*0.16666667;dfy=(cy1-y1)*0.75+tmpy+dddfy*0.16666667;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx;dfy+=ddfy;ddfx+=dddfx;ddfy+=dddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx;dfy+=ddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx+dddfx;dfy+=ddfy+dddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);curves[i]=pathLength;x1=x2;y1=y2;}if(percentPosition){position*=pathLength;}if(percentSpacing){for(var i=0;i<spaceCount;i++){spaces[i]*=pathLength;}}var segments=this._segments;var curveLength=0;for(var i=0,o=0,curve=0,segment=0;i<spaceCount;i++,o+=3){var space=spaces[i];position+=space;var p=position;if(isClosed){p%=pathLength;if(p<0)p+=pathLength;curve=0;}else if(p<0){continue;}else if(p>pathLength){continue;}for(;;curve++){var length_1=curves[curve];if(p>length_1)continue;if(curve===0)p/=length_1;else {var prev=curves[curve-1];p=(p-prev)/(length_1-prev);}break;}if(curve!==preCurve){preCurve=curve;var ii=curve*6;x1=curveVertices[ii];y1=curveVertices[ii+1];cx1=curveVertices[ii+2];cy1=curveVertices[ii+3];cx2=curveVertices[ii+4];cy2=curveVertices[ii+5];x2=curveVertices[ii+6];y2=curveVertices[ii+7];tmpx=(x1-cx1*2+cx2)*0.03;tmpy=(y1-cy1*2+cy2)*0.03;dddfx=((cx1-cx2)*3-x1+x2)*0.006;dddfy=((cy1-cy2)*3-y1+y2)*0.006;ddfx=tmpx*2+dddfx;ddfy=tmpy*2+dddfy;dfx=(cx1-x1)*0.3+tmpx+dddfx*0.16666667;dfy=(cy1-y1)*0.3+tmpy+dddfy*0.16666667;curveLength=Math.sqrt(dfx*dfx+dfy*dfy);segments[0]=curveLength;for(ii=1;ii<8;ii++){dfx+=ddfx;dfy+=ddfy;ddfx+=dddfx;ddfy+=dddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[ii]=curveLength;}dfx+=ddfx;dfy+=ddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[8]=curveLength;dfx+=ddfx+dddfx;dfy+=ddfy+dddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[9]=curveLength;segment=0;}p*=curveLength;for(;;segment++){var length_2=segments[segment];if(p>length_2)continue;if(segment===0)p/=length_2;else {var prev=segments[segment-1];p=segment+(p-prev)/(length_2-prev);}break;}this.addCurvePosition(p*0.1,x1,y1,cx1,cy1,cx2,cy2,x2,y2,positions,o,tangents);}};PathConstraint.prototype.addCurvePosition=function(t,x1,y1,cx1,cy1,cx2,cy2,x2,y2,out,offset,tangents){if(t===0){out[offset]=x1;out[offset+1]=y1;out[offset+2]=0;return;}if(t===1){out[offset]=x2;out[offset+1]=y2;out[offset+2]=0;return;}var mt=1-t;var mt2=mt*mt;var t2=t*t;var a=mt2*mt;var b=mt2*t*3;var c=mt*t2*3;var d=t*t2;var x=a*x1+b*cx1+c*cx2+d*x2;var y=a*y1+b*cy1+c*cy2+d*y2;out[offset]=x;out[offset+1]=y;if(tangents){out[offset+2]=Math.atan2(y-(a*y1+b*cy1+c*cy2),x-(a*x1+b*cx1+c*cx2));}else {out[offset+2]=0;}};PathConstraint.prototype.init=function(constraintData,armature){this._constraintData=constraintData;this._armature=armature;var data=constraintData;this.pathOffset=data.pathDisplayData.vertices.offset;this.position=data.position;this.spacing=data.spacing;this.rotateOffset=data.rotateOffset;this.rotateMix=data.rotateMix;this.translateMix=data.translateMix;this._root=this._armature.getBone(data.root.name);this._target=this._armature.getBone(data.target.name);this._pathSlot=this._armature.getSlot(data.pathSlot.name);for(var i=0,l=data.bones.length;i<l;i++){var bone=this._armature.getBone(data.bones[i].name);if(bone!==null){this._bones.push(bone);}}if(data.rotateMode===2){this._boneLengths.length=this._bones.length;}this._root._hasConstraint=true;};PathConstraint.prototype.update=function(){var pathSlot=this._pathSlot;if(pathSlot._deformVertices===null||pathSlot._deformVertices.verticesData===null||pathSlot._deformVertices.verticesData.offset!==this.pathOffset){return;}var constraintData=this._constraintData;var pathDisplayData=pathSlot._displayData;var isPathVerticeDirty=false;var deformVertices=pathSlot._deformVertices;if(this._root._childrenTransformDirty){this._updatePathVertices(pathDisplayData.vertices);isPathVerticeDirty=true;}else if(deformVertices!==null&&(deformVertices.verticesDirty||deformVertices.isBonesUpdate())){this._updatePathVertices(pathDisplayData.vertices);deformVertices.verticesDirty=false;isPathVerticeDirty=true;}if(!isPathVerticeDirty&&!this.dirty){return;}var positionMode=constraintData.positionMode;var spacingMode=constraintData.spacingMode;var rotateMode=constraintData.rotateMode;var bones=this._bones;var isLengthMode=spacingMode===0;var isChainScaleMode=rotateMode===2;var isTangentMode=rotateMode===0;var boneCount=bones.length;var spacesCount=isTangentMode?boneCount:boneCount+1;var spacing=this.spacing;var spaces=this._spaces;spaces.length=spacesCount;if(isChainScaleMode||isLengthMode){spaces[0]=0;for(var i=0,l=spacesCount-1;i<l;i++){var bone=bones[i];bone.updateByConstraint();var boneLength=bone._boneData.length;var matrix=bone.globalTransformMatrix;var x=boneLength*matrix.a;var y=boneLength*matrix.b;var len=Math.sqrt(x*x+y*y);if(isChainScaleMode){this._boneLengths[i]=len;}spaces[i+1]=(boneLength+spacing)*len/boneLength;}}else {for(var i=0;i<spacesCount;i++){spaces[i]=spacing;}}this._computeBezierCurve(pathDisplayData,spacesCount,isTangentMode,positionMode===1,spacingMode===2);var positions=this._positions;var rotateOffset=this.rotateOffset;var boneX=positions[0],boneY=positions[1];var tip;if(rotateOffset===0){tip=rotateMode===1;}else {tip=false;var bone=pathSlot.parent;if(bone!==null){var matrix=bone.globalTransformMatrix;rotateOffset*=matrix.a*matrix.d-matrix.b*matrix.c>0?dragonBones.Transform.DEG_RAD:-dragonBones.Transform.DEG_RAD;}}var rotateMix=this.rotateMix;var translateMix=this.translateMix;for(var i=0,p=3;i<boneCount;i++,p+=3){var bone=bones[i];bone.updateByConstraint();var matrix=bone.globalTransformMatrix;matrix.tx+=(boneX-matrix.tx)*translateMix;matrix.ty+=(boneY-matrix.ty)*translateMix;var x=positions[p],y=positions[p+1];var dx=x-boneX,dy=y-boneY;if(isChainScaleMode){var lenght=this._boneLengths[i];var s=(Math.sqrt(dx*dx+dy*dy)/lenght-1)*rotateMix+1;matrix.a*=s;matrix.b*=s;}boneX=x;boneY=y;if(rotateMix>0){var a=matrix.a,b=matrix.b,c=matrix.c,d=matrix.d,r=void 0,cos=void 0,sin=void 0;if(isTangentMode){r=positions[p-1];}else {r=Math.atan2(dy,dx);}r-=Math.atan2(b,a);if(tip){cos=Math.cos(r);sin=Math.sin(r);var length_3=bone._boneData.length;boneX+=(length_3*(cos*a-sin*b)-dx)*rotateMix;boneY+=(length_3*(sin*a+cos*b)-dy)*rotateMix;}else {r+=rotateOffset;}if(r>dragonBones.Transform.PI){r-=dragonBones.Transform.PI_D;}else if(r<-dragonBones.Transform.PI){r+=dragonBones.Transform.PI_D;}r*=rotateMix;cos=Math.cos(r);sin=Math.sin(r);matrix.a=cos*a-sin*b;matrix.b=sin*a+cos*b;matrix.c=cos*c-sin*d;matrix.d=sin*c+cos*d;}bone.global.fromMatrix(matrix);}this.dirty=false;};PathConstraint.prototype.invalidUpdate=function(){};return PathConstraint;}(Constraint);dragonBones.PathConstraint=PathConstraint;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var WorldClock=function(){function WorldClock(time){if(time===void 0){time=0.0;}this.time=0.0;this.timeScale=1.0;this._systemTime=0.0;this._animatebles=[];this._clock=null;this.time=time;this._systemTime=new Date().getTime()*0.001;}WorldClock.prototype.advanceTime=function(passedTime){if(passedTime!==passedTime){passedTime=0.0;}var currentTime=Date.now()*0.001;if(passedTime<0.0){passedTime=currentTime-this._systemTime;}this._systemTime=currentTime;if(this.timeScale!==1.0){passedTime*=this.timeScale;}if(passedTime===0.0){return;}if(passedTime<0.0){this.time-=passedTime;}else {this.time+=passedTime;}var i=0,r=0,l=this._animatebles.length;for(;i<l;++i){var animatable=this._animatebles[i];if(animatable!==null){if(r>0){this._animatebles[i-r]=animatable;this._animatebles[i]=null;}animatable.advanceTime(passedTime);}else {r++;}}if(r>0){l=this._animatebles.length;for(;i<l;++i){var animateble=this._animatebles[i];if(animateble!==null){this._animatebles[i-r]=animateble;}else {r++;}}this._animatebles.length-=r;}};WorldClock.prototype.contains=function(value){if(value===this){return false;}var ancestor=value;while(ancestor!==this&&ancestor!==null){ancestor=ancestor.clock;}return ancestor===this;};WorldClock.prototype.add=function(value){if(this._animatebles.indexOf(value)<0){this._animatebles.push(value);value.clock=this;}};WorldClock.prototype.remove=function(value){var index=this._animatebles.indexOf(value);if(index>=0){this._animatebles[index]=null;value.clock=null;}};WorldClock.prototype.clear=function(){for(var _i=0,_a=this._animatebles;_i<_a.length;_i++){var animatable=_a[_i];if(animatable!==null){animatable.clock=null;}}};Object.defineProperty(WorldClock.prototype,"clock",{get:function(){return this._clock;},set:function(value){if(this._clock===value){return;}if(this._clock!==null){this._clock.remove(this);}this._clock=value;if(this._clock!==null){this._clock.add(this);}},enumerable:true,configurable:true});WorldClock.clock=new WorldClock();return WorldClock;}();dragonBones.WorldClock=WorldClock;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var Animation=function(_super){__extends(Animation,_super);function Animation(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._animationNames=[];_this._animationStates=[];_this._animations={};_this._animationConfig=null;return _this;}Animation.toString=function(){return "[class dragonBones.Animation]";};Animation.prototype._onClear=function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.returnToPool();}for(var k in this._animations){delete this._animations[k];}if(this._animationConfig!==null){this._animationConfig.returnToPool();}this.timeScale=1.0;this._lockUpdate=false;this._animationDirty=false;this._inheritTimeScale=1.0;this._animationNames.length=0;this._animationStates.length=0;this._armature=null;this._animationConfig=null;this._lastAnimationState=null;};Animation.prototype._fadeOut=function(animationConfig){switch(animationConfig.fadeOutMode){case 1:for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(animationState._parent!==null){continue;}if(animationState.layer===animationConfig.layer){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 2:for(var _b=0,_c=this._animationStates;_b<_c.length;_b++){var animationState=_c[_b];if(animationState._parent!==null){continue;}if(animationState.group===animationConfig.group){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 3:for(var _d=0,_e=this._animationStates;_d<_e.length;_d++){var animationState=_e[_d];if(animationState._parent!==null){continue;}if(animationState.layer===animationConfig.layer&&animationState.group===animationConfig.group){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 4:for(var _f=0,_g=this._animationStates;_f<_g.length;_f++){var animationState=_g[_f];if(animationState._parent!==null){continue;}animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}break;}};Animation.prototype.init=function(armature){if(this._armature!==null){return;}this._armature=armature;this._animationConfig=dragonBones.BaseObject.borrowObject(dragonBones.AnimationConfig);};Animation.prototype.advanceTime=function(passedTime){if(passedTime<0.0){passedTime=-passedTime;}if(this._armature.inheritAnimation&&this._armature._parent!==null){this._inheritTimeScale=this._armature._parent._armature.animation._inheritTimeScale*this.timeScale;}else {this._inheritTimeScale=this.timeScale;}if(this._inheritTimeScale!==1.0){passedTime*=this._inheritTimeScale;}var animationStateCount=this._animationStates.length;if(animationStateCount===1){var animationState=this._animationStates[0];if(animationState._fadeState>0&&animationState._subFadeState>0){this._armature._dragonBones.bufferObject(animationState);this._animationStates.length=0;this._lastAnimationState=null;}else {var animationData=animationState._animationData;var cacheFrameRate=animationData.cacheFrameRate;if(this._animationDirty&&cacheFrameRate>0.0){this._animationDirty=false;for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];bone._cachedFrameIndices=animationData.getBoneCachedFrameIndices(bone.name);}for(var _b=0,_c=this._armature.getSlots();_b<_c.length;_b++){var slot=_c[_b];var rawDisplayDatas=slot.rawDisplayDatas;if(rawDisplayDatas!==null&&rawDisplayDatas.length>0){var rawDsplayData=rawDisplayDatas[0];if(rawDsplayData!==null){if(rawDsplayData.parent===this._armature.armatureData.defaultSkin){slot._cachedFrameIndices=animationData.getSlotCachedFrameIndices(slot.name);continue;}}}slot._cachedFrameIndices=null;}}animationState.advanceTime(passedTime,cacheFrameRate);}}else if(animationStateCount>1){for(var i=0,r=0;i<animationStateCount;++i){var animationState=this._animationStates[i];if(animationState._fadeState>0&&animationState._subFadeState>0){r++;this._armature._dragonBones.bufferObject(animationState);this._animationDirty=true;if(this._lastAnimationState===animationState){this._lastAnimationState=null;}}else {if(r>0){this._animationStates[i-r]=animationState;}animationState.advanceTime(passedTime,0.0);}if(i===animationStateCount-1&&r>0){this._animationStates.length-=r;if(this._lastAnimationState===null&&this._animationStates.length>0){this._lastAnimationState=this._animationStates[this._animationStates.length-1];}}}this._armature._cacheFrameIndex=-1;}else {this._armature._cacheFrameIndex=-1;}};Animation.prototype.reset=function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.returnToPool();}this._animationDirty=false;this._animationConfig.clear();this._animationStates.length=0;this._lastAnimationState=null;};Animation.prototype.stop=function(animationName){if(animationName===void 0){animationName=null;}if(animationName!==null){var animationState=this.getState(animationName);if(animationState!==null){animationState.stop();}}else {for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.stop();}}};Animation.prototype.playConfig=function(animationConfig){var animationName=animationConfig.animation;if(!(animationName in this._animations)){console.warn("Non-existent animation.\n","DragonBones name: "+this._armature.armatureData.parent.name,"Armature name: "+this._armature.name,"Animation name: "+animationName);return null;}var animationData=this._animations[animationName];if(animationConfig.fadeOutMode===5){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState_1=_a[_i];if(animationState_1._animationData===animationData){return animationState_1;}}}if(this._animationStates.length===0){animationConfig.fadeInTime=0.0;}else if(animationConfig.fadeInTime<0.0){animationConfig.fadeInTime=animationData.fadeInTime;}if(animationConfig.fadeOutTime<0.0){animationConfig.fadeOutTime=animationConfig.fadeInTime;}if(animationConfig.timeScale<=-100.0){animationConfig.timeScale=1.0/animationData.scale;}if(animationData.frameCount>1){if(animationConfig.position<0.0){animationConfig.position%=animationData.duration;animationConfig.position=animationData.duration-animationConfig.position;}else if(animationConfig.position===animationData.duration){animationConfig.position-=0.000001;}else if(animationConfig.position>animationData.duration){animationConfig.position%=animationData.duration;}if(animationConfig.duration>0.0&&animationConfig.position+animationConfig.duration>animationData.duration){animationConfig.duration=animationData.duration-animationConfig.position;}if(animationConfig.playTimes<0){animationConfig.playTimes=animationData.playTimes;}}else {animationConfig.playTimes=1;animationConfig.position=0.0;if(animationConfig.duration>0.0){animationConfig.duration=0.0;}}if(animationConfig.duration===0.0){animationConfig.duration=-1.0;}this._fadeOut(animationConfig);var animationState=dragonBones.BaseObject.borrowObject(dragonBones.AnimationState);animationState.init(this._armature,animationData,animationConfig);this._animationDirty=true;this._armature._cacheFrameIndex=-1;if(this._animationStates.length>0){var added=false;for(var i=0,l=this._animationStates.length;i<l;++i){if(animationState.layer>this._animationStates[i].layer){added=true;this._animationStates.splice(i,0,animationState);break;}else if(i!==l-1&&animationState.layer>this._animationStates[i+1].layer){added=true;this._animationStates.splice(i+1,0,animationState);break;}}if(!added){this._animationStates.push(animationState);}}else {this._animationStates.push(animationState);}for(var _b=0,_c=this._armature.getSlots();_b<_c.length;_b++){var slot=_c[_b];var childArmature=slot.childArmature;if(childArmature!==null&&childArmature.inheritAnimation&&childArmature.animation.hasAnimation(animationName)&&childArmature.animation.getState(animationName)===null){childArmature.animation.fadeIn(animationName);}}var isLocked=false;for(var k in animationData.animationTimelines){if(!this._lockUpdate){isLocked=true;this._lockUpdate=true;}var childAnimatiionState=this.fadeIn(k,animationConfig.fadeInTime,1,animationState.layer,null,0);if(childAnimatiionState!==null){childAnimatiionState.resetToPose=false;childAnimatiionState._parent=animationState;childAnimatiionState.stop();}}if(isLocked){this._lockUpdate=false;}if(!this._lockUpdate){if(animationConfig.fadeInTime<=0.0){this._armature.advanceTime(0.0);}this._lastAnimationState=animationState;}return animationState;};Animation.prototype.play=function(animationName,playTimes){if(animationName===void 0){animationName=null;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName!==null?animationName:"";if(animationName!==null&&animationName.length>0){this.playConfig(this._animationConfig);}else if(this._lastAnimationState===null){var defaultAnimation=this._armature.armatureData.defaultAnimation;if(defaultAnimation!==null){this._animationConfig.animation=defaultAnimation.name;this.playConfig(this._animationConfig);}}else if(!this._lastAnimationState.isPlaying&&!this._lastAnimationState.isCompleted){this._lastAnimationState.play();}else {this._animationConfig.animation=this._lastAnimationState.name;this.playConfig(this._animationConfig);}return this._lastAnimationState;};Animation.prototype.fadeIn=function(animationName,fadeInTime,playTimes,layer,group,fadeOutMode){if(fadeInTime===void 0){fadeInTime=-1.0;}if(playTimes===void 0){playTimes=-1;}if(layer===void 0){layer=0;}if(group===void 0){group=null;}if(fadeOutMode===void 0){fadeOutMode=3;}this._animationConfig.clear();this._animationConfig.fadeOutMode=fadeOutMode;this._animationConfig.playTimes=playTimes;this._animationConfig.layer=layer;this._animationConfig.fadeInTime=fadeInTime;this._animationConfig.animation=animationName;this._animationConfig.group=group!==null?group:"";return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByTime=function(animationName,time,playTimes){if(time===void 0){time=0.0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.position=time;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByFrame=function(animationName,frame,playTimes){if(frame===void 0){frame=0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;var animationData=animationName in this._animations?this._animations[animationName]:null;if(animationData!==null){this._animationConfig.position=animationData.duration*frame/animationData.frameCount;}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByProgress=function(animationName,progress,playTimes){if(progress===void 0){progress=0.0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;var animationData=animationName in this._animations?this._animations[animationName]:null;if(animationData!==null){this._animationConfig.position=animationData.duration*(progress>0.0?progress:0.0);}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndStopByTime=function(animationName,time){if(time===void 0){time=0.0;}var animationState=this.gotoAndPlayByTime(animationName,time,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.gotoAndStopByFrame=function(animationName,frame){if(frame===void 0){frame=0;}var animationState=this.gotoAndPlayByFrame(animationName,frame,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.gotoAndStopByProgress=function(animationName,progress){if(progress===void 0){progress=0.0;}var animationState=this.gotoAndPlayByProgress(animationName,progress,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.getState=function(animationName){var i=this._animationStates.length;while(i--){var animationState=this._animationStates[i];if(animationState.name===animationName){return animationState;}}return null;};Animation.prototype.hasAnimation=function(animationName){return animationName in this._animations;};Animation.prototype.getStates=function(){return this._animationStates;};Object.defineProperty(Animation.prototype,"isPlaying",{get:function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(animationState.isPlaying){return true;}}return false;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"isCompleted",{get:function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(!animationState.isCompleted){return false;}}return this._animationStates.length>0;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"lastAnimationName",{get:function(){return this._lastAnimationState!==null?this._lastAnimationState.name:"";},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationNames",{get:function(){return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animations",{get:function(){return this._animations;},set:function(value){if(this._animations===value){return;}this._animationNames.length=0;for(var k in this._animations){delete this._animations[k];}for(var k in value){this._animationNames.push(k);this._animations[k]=value[k];}},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationConfig",{get:function(){this._animationConfig.clear();return this._animationConfig;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"lastAnimationState",{get:function(){return this._lastAnimationState;},enumerable:true,configurable:true});Animation.prototype.gotoAndPlay=function(animationName,fadeInTime,duration,playTimes,layer,group,fadeOutMode,pauseFadeOut,pauseFadeIn){if(fadeInTime===void 0){fadeInTime=-1;}if(duration===void 0){duration=-1;}if(playTimes===void 0){playTimes=-1;}if(layer===void 0){layer=0;}if(group===void 0){group=null;}if(fadeOutMode===void 0){fadeOutMode=3;}console.warn("Deprecated.");this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.fadeOutMode=fadeOutMode;this._animationConfig.playTimes=playTimes;this._animationConfig.layer=layer;this._animationConfig.fadeInTime=fadeInTime;this._animationConfig.animation=animationName;this._animationConfig.group=group!==null?group:"";var animationData=this._animations[animationName];if(animationData&&duration>0.0){this._animationConfig.timeScale=animationData.duration/duration;}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndStop=function(animationName,time){if(time===void 0){time=0;}console.warn("Deprecated.");return this.gotoAndStopByTime(animationName,time);};Object.defineProperty(Animation.prototype,"animationList",{get:function(){console.warn("Deprecated.");return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationDataList",{get:function(){console.warn("Deprecated.");var list=[];for(var i=0,l=this._animationNames.length;i<l;++i){list.push(this._animations[this._animationNames[i]]);}return list;},enumerable:true,configurable:true});return Animation;}(dragonBones.BaseObject);dragonBones.Animation=Animation;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var AnimationState=function(_super){__extends(AnimationState,_super);function AnimationState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._blendState=new BlendState();_this._boneMask=[];_this._boneTimelines=[];_this._surfaceTimelines=[];_this._slotTimelines=[];_this._constraintTimelines=[];_this._animationTimelines=[];_this._poseTimelines=[];_this._bonePoses={};_this._actionTimeline=null;_this._zOrderTimeline=null;_this._parent=null;return _this;}AnimationState.toString=function(){return "[class dragonBones.AnimationState]";};AnimationState.prototype._onClear=function(){for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.returnToPool();}for(var _b=0,_c=this._surfaceTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.returnToPool();}for(var _d=0,_e=this._slotTimelines;_d<_e.length;_d++){var timeline=_e[_d];timeline.returnToPool();}for(var _f=0,_g=this._constraintTimelines;_f<_g.length;_f++){var timeline=_g[_f];timeline.returnToPool();}for(var _h=0,_j=this._animationTimelines;_h<_j.length;_h++){var timeline=_j[_h];timeline.returnToPool();}for(var k in this._bonePoses){this._bonePoses[k].returnToPool();delete this._bonePoses[k];}if(this._actionTimeline!==null){this._actionTimeline.returnToPool();}if(this._zOrderTimeline!==null){this._zOrderTimeline.returnToPool();}this.actionEnabled=false;this.additiveBlending=false;this.displayControl=false;this.resetToPose=false;this.playTimes=1;this.layer=0;this.timeScale=1.0;this.weight=1.0;this.autoFadeOutTime=0.0;this.fadeTotalTime=0.0;this.name="";this.group="";this._timelineDirty=2;this._playheadState=0;this._fadeState=-1;this._subFadeState=-1;this._position=0.0;this._duration=0.0;this._fadeTime=0.0;this._time=0.0;this._fadeProgress=0.0;this._weightResult=0.0;this._blendState.clear();this._boneMask.length=0;this._boneTimelines.length=0;this._surfaceTimelines.length=0;this._slotTimelines.length=0;this._constraintTimelines.length=0;this._animationTimelines.length=0;this._poseTimelines.length=0;this._animationData=null;this._armature=null;this._actionTimeline=null;this._zOrderTimeline=null;this._parent=null;};AnimationState.prototype._updateTimelines=function(){{for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];var timelineDatas=this._animationData.getConstraintTimelines(constraint.name);if(timelineDatas!==null){for(var _b=0,timelineDatas_1=timelineDatas;_b<timelineDatas_1.length;_b++){var timelineData=timelineDatas_1[_b];switch(timelineData.type){case 30:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintTimelineState);timeline.constraint=constraint;timeline.init(this._armature,this,timelineData);this._constraintTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintTimelineState);timeline.constraint=constraint;timeline.init(this._armature,this,null);this._constraintTimelines.push(timeline);this._poseTimelines.push(timeline);}}}{for(var _c=0,_d=this._armature.animation.getStates();_c<_d.length;_c++){var animationState=_d[_c];if(animationState._parent!==this){continue;}var timelineDatas=this._animationData.getAnimationTimelines(animationState.name);if(timelineDatas===null){continue;}for(var _e=0,timelineDatas_2=timelineDatas;_e<timelineDatas_2.length;_e++){var timelineData=timelineDatas_2[_e];switch(timelineData.type){case 40:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.AnimationTimelineState);timeline.animationState=animationState;timeline.init(this._armature,this,timelineData);this._animationTimelines.push(timeline);break;}}}}}};AnimationState.prototype._updateBoneAndSlotTimelines=function(){{var boneTimelines={};for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];var timelineName=timeline.bone.name;if(!(timelineName in boneTimelines)){boneTimelines[timelineName]=[];}boneTimelines[timelineName].push(timeline);}for(var _b=0,_c=this._armature.getBones();_b<_c.length;_b++){var bone=_c[_b];var timelineName=bone.name;if(!this.containsBoneMask(timelineName)){continue;}if(timelineName in boneTimelines){delete boneTimelines[timelineName];}else if(bone._boneData.type===0){var timelineDatas=this._animationData.getBoneTimelines(timelineName);var bonePose=timelineName in this._bonePoses?this._bonePoses[timelineName]:this._bonePoses[timelineName]=dragonBones.BaseObject.borrowObject(BonePose);if(timelineDatas!==null){for(var _d=0,timelineDatas_3=timelineDatas;_d<timelineDatas_3.length;_d++){var timelineData=timelineDatas_3[_d];switch(timelineData.type){case 10:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneAllTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 11:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneTranslateTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 12:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneRotateTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 13:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneScaleTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneAllTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,null);this._boneTimelines.push(timeline);this._poseTimelines.push(timeline);}}else if(bone._boneData.type===1){var timelineDatas=this._animationData.getSurfaceTimelines(timelineName);if(timelineDatas!==null){for(var _e=0,timelineDatas_4=timelineDatas;_e<timelineDatas_4.length;_e++){var timelineData=timelineDatas_4[_e];switch(timelineData.type){case 50:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceTimelineState);timeline.surface=bone;timeline.init(this._armature,this,timelineData);this._surfaceTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceTimelineState);timeline.surface=bone;timeline.init(this._armature,this,null);this._surfaceTimelines.push(timeline);this._poseTimelines.push(timeline);}}}for(var k in boneTimelines){for(var _f=0,_g=boneTimelines[k];_f<_g.length;_f++){var timeline=_g[_f];this._boneTimelines.splice(this._boneTimelines.indexOf(timeline),1);timeline.returnToPool();}}}{var slotTimelines={};var ffdFlags=[];for(var _h=0,_j=this._slotTimelines;_h<_j.length;_h++){var timeline=_j[_h];var timelineName=timeline.slot.name;if(!(timelineName in slotTimelines)){slotTimelines[timelineName]=[];}slotTimelines[timelineName].push(timeline);}for(var _k=0,_l=this._armature.getSlots();_k<_l.length;_k++){var slot=_l[_k];var boneName=slot.parent.name;if(!this.containsBoneMask(boneName)){continue;}var timelineName=slot.name;var timelineDatas=this._animationData.getSlotTimelines(timelineName);if(timelineName in slotTimelines){delete slotTimelines[timelineName];}else {var displayIndexFlag=false;var colorFlag=false;ffdFlags.length=0;if(timelineDatas!==null){for(var _m=0,timelineDatas_5=timelineDatas;_m<timelineDatas_5.length;_m++){var timelineData=timelineDatas_5[_m];switch(timelineData.type){case 20:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotDislayTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);displayIndexFlag=true;break;}case 21:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotColorTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);colorFlag=true;break;}case 22:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.DeformTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);ffdFlags.push(timeline.vertexOffset);break;}}}}if(this.resetToPose){if(!displayIndexFlag){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotDislayTimelineState);timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}if(!colorFlag){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotColorTimelineState);timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}if(slot.rawDisplayDatas!==null){for(var _o=0,_p=slot.rawDisplayDatas;_o<_p.length;_o++){var displayData=_p[_o];if(displayData!==null&&displayData.type===2){var meshOffset=displayData.vertices.offset;if(ffdFlags.indexOf(meshOffset)<0){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.DeformTimelineState);timeline.vertexOffset=meshOffset;timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}}}}}}}for(var k in slotTimelines){for(var _q=0,_r=slotTimelines[k];_q<_r.length;_q++){var timeline=_r[_q];this._slotTimelines.splice(this._slotTimelines.indexOf(timeline),1);timeline.returnToPool();}}}};AnimationState.prototype._advanceFadeTime=function(passedTime){var isFadeOut=this._fadeState>0;if(this._subFadeState<0){this._subFadeState=0;var eventType=isFadeOut?dragonBones.EventObject.FADE_OUT:dragonBones.EventObject.FADE_IN;if(this._armature.eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=eventType;eventObject.armature=this._armature;eventObject.animationState=this;this._armature._dragonBones.bufferEvent(eventObject);}}if(passedTime<0.0){passedTime=-passedTime;}this._fadeTime+=passedTime;if(this._fadeTime>=this.fadeTotalTime){this._subFadeState=1;this._fadeProgress=isFadeOut?0.0:1.0;}else if(this._fadeTime>0.0){this._fadeProgress=isFadeOut?1.0-this._fadeTime/this.fadeTotalTime:this._fadeTime/this.fadeTotalTime;}else {this._fadeProgress=isFadeOut?1.0:0.0;}if(this._subFadeState>0){if(!isFadeOut){this._playheadState|=1;this._fadeState=0;}var eventType=isFadeOut?dragonBones.EventObject.FADE_OUT_COMPLETE:dragonBones.EventObject.FADE_IN_COMPLETE;if(this._armature.eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=eventType;eventObject.armature=this._armature;eventObject.animationState=this;this._armature._dragonBones.bufferEvent(eventObject);}}};AnimationState.prototype.init=function(armature,animationData,animationConfig){if(this._armature!==null){return;}this._armature=armature;this._animationData=animationData;this.resetToPose=animationConfig.resetToPose;this.additiveBlending=animationConfig.additiveBlending;this.displayControl=animationConfig.displayControl;this.actionEnabled=animationConfig.actionEnabled;this.layer=animationConfig.layer;this.playTimes=animationConfig.playTimes;this.timeScale=animationConfig.timeScale;this.fadeTotalTime=animationConfig.fadeInTime;this.autoFadeOutTime=animationConfig.autoFadeOutTime;this.weight=animationConfig.weight;this.name=animationConfig.name.length>0?animationConfig.name:animationConfig.animation;this.group=animationConfig.group;if(animationConfig.pauseFadeIn){this._playheadState=2;}else {this._playheadState=3;}if(animationConfig.duration<0.0){this._position=0.0;this._duration=this._animationData.duration;if(animationConfig.position!==0.0){if(this.timeScale>=0.0){this._time=animationConfig.position;}else {this._time=animationConfig.position-this._duration;}}else {this._time=0.0;}}else {this._position=animationConfig.position;this._duration=animationConfig.duration;this._time=0.0;}if(this.timeScale<0.0&&this._time===0.0){this._time=-0.000001;}if(this.fadeTotalTime<=0.0){this._fadeProgress=0.999999;}if(animationConfig.boneMask.length>0){this._boneMask.length=animationConfig.boneMask.length;for(var i=0,l=this._boneMask.length;i<l;++i){this._boneMask[i]=animationConfig.boneMask[i];}}this._actionTimeline=dragonBones.BaseObject.borrowObject(dragonBones.ActionTimelineState);this._actionTimeline.init(this._armature,this,this._animationData.actionTimeline);this._actionTimeline.currentTime=this._time;if(this._actionTimeline.currentTime<0.0){this._actionTimeline.currentTime=this._duration-this._actionTimeline.currentTime;}if(this._animationData.zOrderTimeline!==null){this._zOrderTimeline=dragonBones.BaseObject.borrowObject(dragonBones.ZOrderTimelineState);this._zOrderTimeline.init(this._armature,this,this._animationData.zOrderTimeline);}};AnimationState.prototype.advanceTime=function(passedTime,cacheFrameRate){this._blendState.dirty=false;if(this._fadeState!==0||this._subFadeState!==0){this._advanceFadeTime(passedTime);}if(this._playheadState===3){if(this.timeScale!==1.0){passedTime*=this.timeScale;}this._time+=passedTime;}if(this._timelineDirty!==0){if(this._timelineDirty===2){this._updateTimelines();}this._timelineDirty=0;this._updateBoneAndSlotTimelines();}if(this.weight===0.0){return;}var isCacheEnabled=this._fadeState===0&&cacheFrameRate>0.0;var isUpdateTimeline=true;var isUpdateBoneTimeline=true;var time=this._time;this._weightResult=this.weight*this._fadeProgress;if(this._parent!==null){this._weightResult*=this._parent._weightResult/this._parent._fadeProgress;}if(this._actionTimeline.playState<=0){this._actionTimeline.update(time);}if(isCacheEnabled){var internval=cacheFrameRate*2.0;this._actionTimeline.currentTime=Math.floor(this._actionTimeline.currentTime*internval)/internval;}if(this._zOrderTimeline!==null&&this._zOrderTimeline.playState<=0){this._zOrderTimeline.update(time);}if(isCacheEnabled){var cacheFrameIndex=Math.floor(this._actionTimeline.currentTime*cacheFrameRate);if(this._armature._cacheFrameIndex===cacheFrameIndex){isUpdateTimeline=false;isUpdateBoneTimeline=false;}else {this._armature._cacheFrameIndex=cacheFrameIndex;if(this._animationData.cachedFrames[cacheFrameIndex]){isUpdateBoneTimeline=false;}else {this._animationData.cachedFrames[cacheFrameIndex]=true;}}}if(isUpdateTimeline){if(isUpdateBoneTimeline){for(var i=0,l=this._boneTimelines.length;i<l;++i){var timeline=this._boneTimelines[i];if(timeline.playState<=0){timeline.update(time);}if(i===l-1||timeline.bone!==this._boneTimelines[i+1].bone){var state=timeline.bone._blendState.update(this._weightResult,this.layer);if(state!==0){timeline.blend(state);}}}}for(var i=0,l=this._surfaceTimelines.length;i<l;++i){var timeline=this._surfaceTimelines[i];var state=timeline.surface._blendState.update(this._weightResult,this.layer);if(timeline.playState<=0){timeline.update(time);}if(state!==0){timeline.blend(state);}}if(this.displayControl){for(var i=0,l=this._slotTimelines.length;i<l;++i){var timeline=this._slotTimelines[i];var displayController=timeline.slot.displayController;if(displayController===null||displayController===this.name||displayController===this.group){if(timeline.playState<=0){timeline.update(time);}}}}for(var i=0,l=this._constraintTimelines.length;i<l;++i){var timeline=this._constraintTimelines[i];if(timeline.playState<=0){timeline.update(time);}}for(var i=0,l=this._animationTimelines.length;i<l;++i){var timeline=this._animationTimelines[i];var state=timeline.animationState._blendState.update(this._weightResult,this.layer);if(timeline.playState<=0){timeline.update(time);}if(state!==0){timeline.blend(state);}}}if(this._fadeState===0){if(this._subFadeState>0){this._subFadeState=0;if(this._poseTimelines.length>0){for(var _i=0,_a=this._poseTimelines;_i<_a.length;_i++){var timeline=_a[_i];if(timeline instanceof dragonBones.BoneTimelineState){this._boneTimelines.splice(this._boneTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.SurfaceTimelineState){this._surfaceTimelines.splice(this._surfaceTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.SlotTimelineState){this._slotTimelines.splice(this._slotTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.ConstraintTimelineState){this._constraintTimelines.splice(this._constraintTimelines.indexOf(timeline),1);}timeline.returnToPool();}this._poseTimelines.length=0;}}if(this._actionTimeline.playState>0){if(this.autoFadeOutTime>=0.0){this.fadeOut(this.autoFadeOutTime);}}}};AnimationState.prototype.play=function(){this._playheadState=3;};AnimationState.prototype.stop=function(){this._playheadState&=1;};AnimationState.prototype.fadeOut=function(fadeOutTime,pausePlayhead){if(pausePlayhead===void 0){pausePlayhead=true;}if(fadeOutTime<0.0){fadeOutTime=0.0;}if(pausePlayhead){this._playheadState&=2;}if(this._fadeState>0){if(fadeOutTime>this.fadeTotalTime-this._fadeTime){return;}}else {this._fadeState=1;this._subFadeState=-1;if(fadeOutTime<=0.0||this._fadeProgress<=0.0){this._fadeProgress=0.000001;}for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.fadeOut();}for(var _b=0,_c=this._surfaceTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.fadeOut();}for(var _d=0,_e=this._slotTimelines;_d<_e.length;_d++){var timeline=_e[_d];timeline.fadeOut();}for(var _f=0,_g=this._constraintTimelines;_f<_g.length;_f++){var timeline=_g[_f];timeline.fadeOut();}for(var _h=0,_j=this._animationTimelines;_h<_j.length;_h++){var timeline=_j[_h];timeline.animationState.fadeOut(fadeOutTime,pausePlayhead);timeline.fadeOut();}}this.displayControl=false;this.fadeTotalTime=this._fadeProgress>0.000001?fadeOutTime/this._fadeProgress:0.0;this._fadeTime=this.fadeTotalTime*(1.0-this._fadeProgress);};AnimationState.prototype.containsBoneMask=function(boneName){return this._boneMask.length===0||this._boneMask.indexOf(boneName)>=0;};AnimationState.prototype.addBoneMask=function(boneName,recursive){if(recursive===void 0){recursive=true;}var currentBone=this._armature.getBone(boneName);if(currentBone===null){return;}if(this._boneMask.indexOf(boneName)<0){this._boneMask.push(boneName);}if(recursive){for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(this._boneMask.indexOf(bone.name)<0&&currentBone.contains(bone)){this._boneMask.push(bone.name);}}}this._timelineDirty=1;};AnimationState.prototype.removeBoneMask=function(boneName,recursive){if(recursive===void 0){recursive=true;}var index=this._boneMask.indexOf(boneName);if(index>=0){this._boneMask.splice(index,1);}if(recursive){var currentBone=this._armature.getBone(boneName);if(currentBone!==null){var bones=this._armature.getBones();if(this._boneMask.length>0){for(var _i=0,bones_1=bones;_i<bones_1.length;_i++){var bone=bones_1[_i];var index_2=this._boneMask.indexOf(bone.name);if(index_2>=0&&currentBone.contains(bone)){this._boneMask.splice(index_2,1);}}}else {for(var _a=0,bones_2=bones;_a<bones_2.length;_a++){var bone=bones_2[_a];if(bone===currentBone){continue;}if(!currentBone.contains(bone)){this._boneMask.push(bone.name);}}}}}this._timelineDirty=1;};AnimationState.prototype.removeAllBoneMask=function(){this._boneMask.length=0;this._timelineDirty=1;};Object.defineProperty(AnimationState.prototype,"isFadeIn",{get:function(){return this._fadeState<0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeOut",{get:function(){return this._fadeState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeComplete",{get:function(){return this._fadeState===0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isPlaying",{get:function(){return (this._playheadState&2)!==0&&this._actionTimeline.playState<=0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isCompleted",{get:function(){return this._actionTimeline.playState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentPlayTimes",{get:function(){return this._actionTimeline.currentPlayTimes;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"totalTime",{get:function(){return this._duration;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentTime",{get:function(){return this._actionTimeline.currentTime;},set:function(value){var currentPlayTimes=this._actionTimeline.currentPlayTimes-(this._actionTimeline.playState>0?1:0);if(value<0||this._duration<value){value=value%this._duration+currentPlayTimes*this._duration;if(value<0){value+=this._duration;}}if(this.playTimes>0&&currentPlayTimes===this.playTimes-1&&value===this._duration){value=this._duration-0.000001;}if(this._time===value){return;}this._time=value;this._actionTimeline.setCurrentTime(this._time);if(this._zOrderTimeline!==null){this._zOrderTimeline.playState=-1;}for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.playState=-1;}for(var _b=0,_c=this._slotTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.playState=-1;}},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"animationData",{get:function(){return this._animationData;},enumerable:true,configurable:true});return AnimationState;}(dragonBones.BaseObject);dragonBones.AnimationState=AnimationState;var BonePose=function(_super){__extends(BonePose,_super);function BonePose(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.current=new dragonBones.Transform();_this.delta=new dragonBones.Transform();_this.result=new dragonBones.Transform();return _this;}BonePose.toString=function(){return "[class dragonBones.BonePose]";};BonePose.prototype._onClear=function(){this.current.identity();this.delta.identity();this.result.identity();};return BonePose;}(dragonBones.BaseObject);dragonBones.BonePose=BonePose;var BlendState=function(){function BlendState(){}BlendState.prototype.update=function(weight,p_layer){if(this.dirty){if(this.leftWeight>0.0){if(this.layer!==p_layer){if(this.layerWeight>=this.leftWeight){this.leftWeight=0.0;return 0;}else {this.layer=p_layer;this.leftWeight-=this.layerWeight;this.layerWeight=0.0;}}}else {return 0;}weight*=this.leftWeight;this.layerWeight+=weight;this.blendWeight=weight;return 2;}this.dirty=true;this.layer=p_layer;this.layerWeight=weight;this.leftWeight=1.0;this.blendWeight=weight;return 1;};BlendState.prototype.clear=function(){this.dirty=false;this.layer=0;this.leftWeight=0.0;this.layerWeight=0.0;this.blendWeight=0.0;};return BlendState;}();dragonBones.BlendState=BlendState;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var TimelineState=function(_super){__extends(TimelineState,_super);function TimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}TimelineState.prototype._onClear=function(){this.playState=-1;this.currentPlayTimes=-1;this.currentTime=-1.0;this._tweenState=0;this._frameRate=0;this._frameValueOffset=0;this._frameCount=0;this._frameOffset=0;this._frameIndex=-1;this._frameRateR=0.0;this._position=0.0;this._duration=0.0;this._timeScale=1.0;this._timeOffset=0.0;this._dragonBonesData=null;this._animationData=null;this._timelineData=null;this._armature=null;this._animationState=null;this._actionTimeline=null;this._frameArray=null;this._frameIntArray=null;this._frameFloatArray=null;this._timelineArray=null;this._frameIndices=null;};TimelineState.prototype._setCurrentTime=function(passedTime){var prevState=this.playState;var prevPlayTimes=this.currentPlayTimes;var prevTime=this.currentTime;if(this._actionTimeline!==null&&this._frameCount<=1){this.playState=this._actionTimeline.playState>=0?1:-1;this.currentPlayTimes=1;this.currentTime=this._actionTimeline.currentTime;}else if(this._actionTimeline===null||this._timeScale!==1.0||this._timeOffset!==0.0){var playTimes=this._animationState.playTimes;var totalTime=playTimes*this._duration;passedTime*=this._timeScale;if(this._timeOffset!==0.0){passedTime+=this._timeOffset*this._animationData.duration;}if(playTimes>0&&(passedTime>=totalTime||passedTime<=-totalTime)){if(this.playState<=0&&this._animationState._playheadState===3){this.playState=1;}this.currentPlayTimes=playTimes;if(passedTime<0.0){this.currentTime=0.0;}else {this.currentTime=this._duration+0.000001;}}else {if(this.playState!==0&&this._animationState._playheadState===3){this.playState=0;}if(passedTime<0.0){passedTime=-passedTime;this.currentPlayTimes=Math.floor(passedTime/this._duration);this.currentTime=this._duration-passedTime%this._duration;}else {this.currentPlayTimes=Math.floor(passedTime/this._duration);this.currentTime=passedTime%this._duration;}}this.currentTime+=this._position;}else {this.playState=this._actionTimeline.playState;this.currentPlayTimes=this._actionTimeline.currentPlayTimes;this.currentTime=this._actionTimeline.currentTime;}if(this.currentPlayTimes===prevPlayTimes&&this.currentTime===prevTime){return false;}if(prevState<0&&this.playState!==prevState||this.playState<=0&&this.currentPlayTimes!==prevPlayTimes){this._frameIndex=-1;}return true;};TimelineState.prototype.init=function(armature,animationState,timelineData){this._armature=armature;this._animationState=animationState;this._timelineData=timelineData;this._actionTimeline=this._animationState._actionTimeline;if(this===this._actionTimeline){this._actionTimeline=null;}this._animationData=this._animationState._animationData;this._frameRate=this._animationData.parent.frameRate;this._frameRateR=1.0/this._frameRate;this._position=this._animationState._position;this._duration=this._animationState._duration;this._dragonBonesData=this._animationData.parent.parent;if(this._timelineData!==null){this._frameIntArray=this._dragonBonesData.frameIntArray;this._frameFloatArray=this._dragonBonesData.frameFloatArray;this._frameArray=this._dragonBonesData.frameArray;this._timelineArray=this._dragonBonesData.timelineArray;this._frameIndices=this._dragonBonesData.frameIndices;this._frameCount=this._timelineArray[this._timelineData.offset+2];this._frameValueOffset=this._timelineArray[this._timelineData.offset+4];this._timeScale=100.0/this._timelineArray[this._timelineData.offset+0];this._timeOffset=this._timelineArray[this._timelineData.offset+1]*0.01;}};TimelineState.prototype.fadeOut=function(){};TimelineState.prototype.update=function(passedTime){if(this._setCurrentTime(passedTime)){if(this._frameCount>1){var timelineFrameIndex=Math.floor(this.currentTime*this._frameRate);var frameIndex=this._frameIndices[this._timelineData.frameIndicesOffset+timelineFrameIndex];if(this._frameIndex!==frameIndex){this._frameIndex=frameIndex;this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+this._frameIndex];this._onArriveAtFrame();}}else if(this._frameIndex<0){this._frameIndex=0;if(this._timelineData!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5];}this._onArriveAtFrame();}if(this._tweenState!==0){this._onUpdateFrame();}}};return TimelineState;}(dragonBones.BaseObject);dragonBones.TimelineState=TimelineState;var TweenTimelineState=function(_super){__extends(TweenTimelineState,_super);function TweenTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}TweenTimelineState._getEasingValue=function(tweenType,progress,easing){var value=progress;switch(tweenType){case 3:value=Math.pow(progress,2.0);break;case 4:value=1.0-Math.pow(1.0-progress,2.0);break;case 5:value=0.5*(1.0-Math.cos(progress*Math.PI));break;}return (value-progress)*easing+progress;};TweenTimelineState._getEasingCurveValue=function(progress,samples,count,offset){if(progress<=0.0){return 0.0;}else if(progress>=1.0){return 1.0;}var segmentCount=count+1;var valueIndex=Math.floor(progress*segmentCount);var fromValue=valueIndex===0?0.0:samples[offset+valueIndex-1];var toValue=valueIndex===segmentCount-1?10000.0:samples[offset+valueIndex];return (fromValue+(toValue-fromValue)*(progress*segmentCount-valueIndex))*0.0001;};TweenTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._tweenType=0;this._curveCount=0;this._framePosition=0.0;this._frameDurationR=0.0;this._tweenProgress=0.0;this._tweenEasing=0.0;};TweenTimelineState.prototype._onArriveAtFrame=function(){if(this._frameCount>1&&(this._frameIndex!==this._frameCount-1||this._animationState.playTimes===0||this._animationState.currentPlayTimes<this._animationState.playTimes-1)){this._tweenType=this._frameArray[this._frameOffset+1];this._tweenState=this._tweenType===0?1:2;if(this._tweenType===2){this._curveCount=this._frameArray[this._frameOffset+2];}else if(this._tweenType!==0&&this._tweenType!==1){this._tweenEasing=this._frameArray[this._frameOffset+2]*0.01;}this._framePosition=this._frameArray[this._frameOffset]*this._frameRateR;if(this._frameIndex===this._frameCount-1){this._frameDurationR=1.0/(this._animationData.duration-this._framePosition);}else {var nextFrameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+this._frameIndex+1];var frameDuration=this._frameArray[nextFrameOffset]*this._frameRateR-this._framePosition;if(frameDuration>0){this._frameDurationR=1.0/frameDuration;}else {this._frameDurationR=0.0;}}}else {this._tweenState=1;}};TweenTimelineState.prototype._onUpdateFrame=function(){if(this._tweenState===2){this._tweenProgress=(this.currentTime-this._framePosition)*this._frameDurationR;if(this._tweenType===2){this._tweenProgress=TweenTimelineState._getEasingCurveValue(this._tweenProgress,this._frameArray,this._curveCount,this._frameOffset+3);}else if(this._tweenType!==1){this._tweenProgress=TweenTimelineState._getEasingValue(this._tweenType,this._tweenProgress,this._tweenEasing);}}else {this._tweenProgress=0.0;}};return TweenTimelineState;}(TimelineState);dragonBones.TweenTimelineState=TweenTimelineState;var BoneTimelineState=function(_super){__extends(BoneTimelineState,_super);function BoneTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.bone=null;this.bonePose=null;};BoneTimelineState.prototype.blend=function(state){var blendWeight=this.bone._blendState.blendWeight;var animationPose=this.bone.animationPose;var result=this.bonePose.result;if(state===2){animationPose.x+=result.x*blendWeight;animationPose.y+=result.y*blendWeight;animationPose.rotation+=result.rotation*blendWeight;animationPose.skew+=result.skew*blendWeight;animationPose.scaleX+=(result.scaleX-1.0)*blendWeight;animationPose.scaleY+=(result.scaleY-1.0)*blendWeight;}else if(blendWeight!==1.0){animationPose.x=result.x*blendWeight;animationPose.y=result.y*blendWeight;animationPose.rotation=result.rotation*blendWeight;animationPose.skew=result.skew*blendWeight;animationPose.scaleX=(result.scaleX-1.0)*blendWeight+1.0;animationPose.scaleY=(result.scaleY-1.0)*blendWeight+1.0;}else {animationPose.x=result.x;animationPose.y=result.y;animationPose.rotation=result.rotation;animationPose.skew=result.skew;animationPose.scaleX=result.scaleX;animationPose.scaleY=result.scaleY;}if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){this.bone._transformDirty=true;}};return BoneTimelineState;}(TweenTimelineState);dragonBones.BoneTimelineState=BoneTimelineState;var SlotTimelineState=function(_super){__extends(SlotTimelineState,_super);function SlotTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}SlotTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.slot=null;};return SlotTimelineState;}(TweenTimelineState);dragonBones.SlotTimelineState=SlotTimelineState;var ConstraintTimelineState=function(_super){__extends(ConstraintTimelineState,_super);function ConstraintTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ConstraintTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.constraint=null;};return ConstraintTimelineState;}(TweenTimelineState);dragonBones.ConstraintTimelineState=ConstraintTimelineState;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var ActionTimelineState=function(_super){__extends(ActionTimelineState,_super);function ActionTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ActionTimelineState.toString=function(){return "[class dragonBones.ActionTimelineState]";};ActionTimelineState.prototype._onCrossFrame=function(frameIndex){var eventDispatcher=this._armature.eventDispatcher;if(this._animationState.actionEnabled){var frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+frameIndex];var actionCount=this._frameArray[frameOffset+1];var actions=this._animationData.parent.actions;for(var i=0;i<actionCount;++i){var actionIndex=this._frameArray[frameOffset+2+i];var action=actions[actionIndex];if(action.type===0){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.time=this._frameArray[frameOffset]/this._frameRate;eventObject.animationState=this._animationState;dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);this._armature._bufferAction(eventObject,true);}else {var eventType=action.type===10?dragonBones.EventObject.FRAME_EVENT:dragonBones.EventObject.SOUND_EVENT;if(action.type===11||eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.time=this._frameArray[frameOffset]/this._frameRate;eventObject.animationState=this._animationState;dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);this._armature._dragonBones.bufferEvent(eventObject);}}}}};ActionTimelineState.prototype._onArriveAtFrame=function(){};ActionTimelineState.prototype._onUpdateFrame=function(){};ActionTimelineState.prototype.update=function(passedTime){var prevState=this.playState;var prevPlayTimes=this.currentPlayTimes;var prevTime=this.currentTime;if(this._setCurrentTime(passedTime)){var eventDispatcher=this._armature.eventDispatcher;if(prevState<0){if(this.playState!==prevState){if(this._animationState.displayControl&&this._animationState.resetToPose){this._armature._sortZOrder(null,0);}prevPlayTimes=this.currentPlayTimes;if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.START)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=dragonBones.EventObject.START;eventObject.armature=this._armature;eventObject.animationState=this._animationState;this._armature._dragonBones.bufferEvent(eventObject);}}else {return;}}var isReverse=this._animationState.timeScale<0.0;var loopCompleteEvent=null;var completeEvent=null;if(this.currentPlayTimes!==prevPlayTimes){if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.LOOP_COMPLETE)){loopCompleteEvent=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);loopCompleteEvent.type=dragonBones.EventObject.LOOP_COMPLETE;loopCompleteEvent.armature=this._armature;loopCompleteEvent.animationState=this._animationState;}if(this.playState>0){if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.COMPLETE)){completeEvent=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);completeEvent.type=dragonBones.EventObject.COMPLETE;completeEvent.armature=this._armature;completeEvent.animationState=this._animationState;}}}if(this._frameCount>1){var timelineData=this._timelineData;var timelineFrameIndex=Math.floor(this.currentTime*this._frameRate);var frameIndex=this._frameIndices[timelineData.frameIndicesOffset+timelineFrameIndex];if(this._frameIndex!==frameIndex){var crossedFrameIndex=this._frameIndex;this._frameIndex=frameIndex;if(this._timelineArray!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+this._frameIndex];if(isReverse){if(crossedFrameIndex<0){var prevFrameIndex=Math.floor(prevTime*this._frameRate);crossedFrameIndex=this._frameIndices[timelineData.frameIndicesOffset+prevFrameIndex];if(this.currentPlayTimes===prevPlayTimes){if(crossedFrameIndex===frameIndex){crossedFrameIndex=-1;}}}while(crossedFrameIndex>=0){var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this._position<=framePosition&&framePosition<=this._position+this._duration){this._onCrossFrame(crossedFrameIndex);}if(loopCompleteEvent!==null&&crossedFrameIndex===0){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}if(crossedFrameIndex>0){crossedFrameIndex--;}else {crossedFrameIndex=this._frameCount-1;}if(crossedFrameIndex===frameIndex){break;}}}else {if(crossedFrameIndex<0){var prevFrameIndex=Math.floor(prevTime*this._frameRate);crossedFrameIndex=this._frameIndices[timelineData.frameIndicesOffset+prevFrameIndex];var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this.currentPlayTimes===prevPlayTimes){if(prevTime<=framePosition){if(crossedFrameIndex>0){crossedFrameIndex--;}else {crossedFrameIndex=this._frameCount-1;}}else if(crossedFrameIndex===frameIndex){crossedFrameIndex=-1;}}}while(crossedFrameIndex>=0){if(crossedFrameIndex<this._frameCount-1){crossedFrameIndex++;}else {crossedFrameIndex=0;}var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this._position<=framePosition&&framePosition<=this._position+this._duration){this._onCrossFrame(crossedFrameIndex);}if(loopCompleteEvent!==null&&crossedFrameIndex===0){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}if(crossedFrameIndex===frameIndex){break;}}}}}}else if(this._frameIndex<0){this._frameIndex=0;if(this._timelineData!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5];var framePosition=this._frameArray[this._frameOffset]/this._frameRate;if(this.currentPlayTimes===prevPlayTimes){if(prevTime<=framePosition){this._onCrossFrame(this._frameIndex);}}else if(this._position<=framePosition){if(!isReverse&&loopCompleteEvent!==null){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}this._onCrossFrame(this._frameIndex);}}}if(loopCompleteEvent!==null){this._armature._dragonBones.bufferEvent(loopCompleteEvent);}if(completeEvent!==null){this._armature._dragonBones.bufferEvent(completeEvent);}}};ActionTimelineState.prototype.setCurrentTime=function(value){this._setCurrentTime(value);this._frameIndex=-1;};return ActionTimelineState;}(dragonBones.TimelineState);dragonBones.ActionTimelineState=ActionTimelineState;var ZOrderTimelineState=function(_super){__extends(ZOrderTimelineState,_super);function ZOrderTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ZOrderTimelineState.toString=function(){return "[class dragonBones.ZOrderTimelineState]";};ZOrderTimelineState.prototype._onArriveAtFrame=function(){if(this.playState>=0){var count=this._frameArray[this._frameOffset+1];if(count>0){this._armature._sortZOrder(this._frameArray,this._frameOffset+2);}else {this._armature._sortZOrder(null,0);}}};ZOrderTimelineState.prototype._onUpdateFrame=function(){};return ZOrderTimelineState;}(dragonBones.TimelineState);dragonBones.ZOrderTimelineState=ZOrderTimelineState;var BoneAllTimelineState=function(_super){__extends(BoneAllTimelineState,_super);function BoneAllTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneAllTimelineState.toString=function(){return "[class dragonBones.BoneAllTimelineState]";};BoneAllTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*6;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=frameFloatArray[valueOffset++]*scale;current.y=frameFloatArray[valueOffset++]*scale;current.rotation=frameFloatArray[valueOffset++];current.skew=frameFloatArray[valueOffset++];current.scaleX=frameFloatArray[valueOffset++];current.scaleY=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.x=frameFloatArray[valueOffset++]*scale-current.x;delta.y=frameFloatArray[valueOffset++]*scale-current.y;delta.rotation=frameFloatArray[valueOffset++]-current.rotation;delta.skew=frameFloatArray[valueOffset++]-current.skew;delta.scaleX=frameFloatArray[valueOffset++]-current.scaleX;delta.scaleY=frameFloatArray[valueOffset++]-current.scaleY;}else {delta.x=0.0;delta.y=0.0;delta.rotation=0.0;delta.skew=0.0;delta.scaleX=0.0;delta.scaleY=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=0.0;current.y=0.0;current.rotation=0.0;current.skew=0.0;current.scaleX=1.0;current.scaleY=1.0;delta.x=0.0;delta.y=0.0;delta.rotation=0.0;delta.skew=0.0;delta.scaleX=0.0;delta.scaleY=0.0;}};BoneAllTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.x=current.x+delta.x*this._tweenProgress;result.y=current.y+delta.y*this._tweenProgress;result.rotation=current.rotation+delta.rotation*this._tweenProgress;result.skew=current.skew+delta.skew*this._tweenProgress;result.scaleX=current.scaleX+delta.scaleX*this._tweenProgress;result.scaleY=current.scaleY+delta.scaleY*this._tweenProgress;};BoneAllTimelineState.prototype.fadeOut=function(){var result=this.bonePose.result;result.rotation=dragonBones.Transform.normalizeRadian(result.rotation);result.skew=dragonBones.Transform.normalizeRadian(result.skew);};return BoneAllTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneAllTimelineState=BoneAllTimelineState;var BoneTranslateTimelineState=function(_super){__extends(BoneTranslateTimelineState,_super);function BoneTranslateTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneTranslateTimelineState.toString=function(){return "[class dragonBones.BoneTranslateTimelineState]";};BoneTranslateTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=frameFloatArray[valueOffset++]*scale;current.y=frameFloatArray[valueOffset++]*scale;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.x=frameFloatArray[valueOffset++]*scale-current.x;delta.y=frameFloatArray[valueOffset++]*scale-current.y;}else {delta.x=0.0;delta.y=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=0.0;current.y=0.0;delta.x=0.0;delta.y=0.0;}};BoneTranslateTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.x=current.x+delta.x*this._tweenProgress;result.y=current.y+delta.y*this._tweenProgress;};return BoneTranslateTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneTranslateTimelineState=BoneTranslateTimelineState;var BoneRotateTimelineState=function(_super){__extends(BoneRotateTimelineState,_super);function BoneRotateTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneRotateTimelineState.toString=function(){return "[class dragonBones.BoneRotateTimelineState]";};BoneRotateTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.rotation=frameFloatArray[valueOffset++];current.skew=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;delta.rotation=dragonBones.Transform.normalizeRadian(frameFloatArray[valueOffset++]-current.rotation);}else {delta.rotation=frameFloatArray[valueOffset++]-current.rotation;}delta.skew=frameFloatArray[valueOffset++]-current.skew;}else {delta.rotation=0.0;delta.skew=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.rotation=0.0;current.skew=0.0;delta.rotation=0.0;delta.skew=0.0;}};BoneRotateTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.rotation=current.rotation+delta.rotation*this._tweenProgress;result.skew=current.skew+delta.skew*this._tweenProgress;};BoneRotateTimelineState.prototype.fadeOut=function(){var result=this.bonePose.result;result.rotation=dragonBones.Transform.normalizeRadian(result.rotation);result.skew=dragonBones.Transform.normalizeRadian(result.skew);};return BoneRotateTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneRotateTimelineState=BoneRotateTimelineState;var BoneScaleTimelineState=function(_super){__extends(BoneScaleTimelineState,_super);function BoneScaleTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneScaleTimelineState.toString=function(){return "[class dragonBones.BoneScaleTimelineState]";};BoneScaleTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.scaleX=frameFloatArray[valueOffset++];current.scaleY=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.scaleX=frameFloatArray[valueOffset++]-current.scaleX;delta.scaleY=frameFloatArray[valueOffset++]-current.scaleY;}else {delta.scaleX=0.0;delta.scaleY=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.scaleX=1.0;current.scaleY=1.0;delta.scaleX=0.0;delta.scaleY=0.0;}};BoneScaleTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.scaleX=current.scaleX+delta.scaleX*this._tweenProgress;result.scaleY=current.scaleY+delta.scaleY*this._tweenProgress;};return BoneScaleTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneScaleTimelineState=BoneScaleTimelineState;var SurfaceTimelineState=function(_super){__extends(SurfaceTimelineState,_super);function SurfaceTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[];_this._delta=[];_this._result=[];return _this;}SurfaceTimelineState.toString=function(){return "[class dragonBones.SurfaceTimelineState]";};SurfaceTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.surface=null;this._frameFloatOffset=0;this._valueCount=0;this._deformCount=0;this._valueOffset=0;this._current.length=0;this._delta.length=0;this._result.length=0;};SurfaceTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*this._valueCount;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;if(this._tweenState===2){var nextValueOffset=valueOffset+this._valueCount;if(this._frameIndex===this._frameCount-1){nextValueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}for(var i=0;i<this._valueCount;++i){this._delta[i]=frameFloatArray[nextValueOffset+i]*scale-(this._current[i]=frameFloatArray[valueOffset+i]*scale);}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=frameFloatArray[valueOffset+i]*scale;}}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=0.0;}}};SurfaceTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this.surface._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}for(var i=0;i<this._valueCount;++i){this._result[i]=this._current[i]+this._delta[i]*this._tweenProgress;}};SurfaceTimelineState.prototype.init=function(armature,animationState,timelineData){_super.prototype.init.call(this,armature,animationState,timelineData);if(this._timelineData!==null){var frameIntOffset=this._animationData.frameIntOffset+this._timelineArray[this._timelineData.offset+3];this._deformCount=this._frameIntArray[frameIntOffset+1];this._valueCount=this._frameIntArray[frameIntOffset+2];this._valueOffset=this._frameIntArray[frameIntOffset+3];this._frameFloatOffset=this._frameIntArray[frameIntOffset+4]+this._animationData.frameFloatOffset;}else {this._deformCount=this.surface._deformVertices.length;this._valueCount=this._deformCount;this._valueOffset=0;this._frameFloatOffset=0;}this._current.length=this._valueCount;this._delta.length=this._valueCount;this._result.length=this._valueCount;for(var i=0;i<this._valueCount;++i){this._delta[i]=0.0;}};SurfaceTimelineState.prototype.blend=function(state){var blendWeight=this.surface._blendState.blendWeight;var result=this.surface._deformVertices;for(var i=0;i<this._deformCount;++i){var value=0.0;if(i<this._valueOffset){value=this._frameFloatArray[this._frameFloatOffset+i];}else if(i<this._valueOffset+this._valueCount){value=this._result[i-this._valueOffset];}else {value=this._frameFloatArray[this._frameFloatOffset+i-this._valueCount];}if(state===2){result[i]+=value*blendWeight;}else if(blendWeight!==1.0){result[i]=value*blendWeight;}else {result[i]=value;}}if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){this.surface._transformDirty=true;}};return SurfaceTimelineState;}(dragonBones.TweenTimelineState);dragonBones.SurfaceTimelineState=SurfaceTimelineState;var SlotDislayTimelineState=function(_super){__extends(SlotDislayTimelineState,_super);function SlotDislayTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}SlotDislayTimelineState.toString=function(){return "[class dragonBones.SlotDislayTimelineState]";};SlotDislayTimelineState.prototype._onArriveAtFrame=function(){if(this.playState>=0){var displayIndex=this._timelineData!==null?this._frameArray[this._frameOffset+1]:this.slot._slotData.displayIndex;if(this.slot.displayIndex!==displayIndex){this.slot._setDisplayIndex(displayIndex,true);}}};return SlotDislayTimelineState;}(dragonBones.SlotTimelineState);dragonBones.SlotDislayTimelineState=SlotDislayTimelineState;var SlotColorTimelineState=function(_super){__extends(SlotColorTimelineState,_super);function SlotColorTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[0,0,0,0,0,0,0,0];_this._delta=[0,0,0,0,0,0,0,0];_this._result=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0];return _this;}SlotColorTimelineState.toString=function(){return "[class dragonBones.SlotColorTimelineState]";};SlotColorTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._dirty=false;};SlotColorTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var intArray=this._dragonBonesData.intArray;var frameIntArray=this._frameIntArray;var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*1;var colorOffset=frameIntArray[valueOffset];if(colorOffset<0){colorOffset+=65536;}this._current[0]=intArray[colorOffset++];this._current[1]=intArray[colorOffset++];this._current[2]=intArray[colorOffset++];this._current[3]=intArray[colorOffset++];this._current[4]=intArray[colorOffset++];this._current[5]=intArray[colorOffset++];this._current[6]=intArray[colorOffset++];this._current[7]=intArray[colorOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){colorOffset=frameIntArray[this._animationData.frameIntOffset+this._frameValueOffset];}else {colorOffset=frameIntArray[valueOffset+1*1];}if(colorOffset<0){colorOffset+=65536;}this._delta[0]=intArray[colorOffset++]-this._current[0];this._delta[1]=intArray[colorOffset++]-this._current[1];this._delta[2]=intArray[colorOffset++]-this._current[2];this._delta[3]=intArray[colorOffset++]-this._current[3];this._delta[4]=intArray[colorOffset++]-this._current[4];this._delta[5]=intArray[colorOffset++]-this._current[5];this._delta[6]=intArray[colorOffset++]-this._current[6];this._delta[7]=intArray[colorOffset++]-this._current[7];}}else {var color=this.slot._slotData.color;this._current[0]=color.alphaMultiplier*100.0;this._current[1]=color.redMultiplier*100.0;this._current[2]=color.greenMultiplier*100.0;this._current[3]=color.blueMultiplier*100.0;this._current[4]=color.alphaOffset;this._current[5]=color.redOffset;this._current[6]=color.greenOffset;this._current[7]=color.blueOffset;}};SlotColorTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this._dirty=true;if(this._tweenState!==2){this._tweenState=0;}this._result[0]=(this._current[0]+this._delta[0]*this._tweenProgress)*0.01;this._result[1]=(this._current[1]+this._delta[1]*this._tweenProgress)*0.01;this._result[2]=(this._current[2]+this._delta[2]*this._tweenProgress)*0.01;this._result[3]=(this._current[3]+this._delta[3]*this._tweenProgress)*0.01;this._result[4]=this._current[4]+this._delta[4]*this._tweenProgress;this._result[5]=this._current[5]+this._delta[5]*this._tweenProgress;this._result[6]=this._current[6]+this._delta[6]*this._tweenProgress;this._result[7]=this._current[7]+this._delta[7]*this._tweenProgress;};SlotColorTimelineState.prototype.fadeOut=function(){this._tweenState=0;this._dirty=false;};SlotColorTimelineState.prototype.update=function(passedTime){_super.prototype.update.call(this,passedTime);if(this._tweenState!==0||this._dirty){var result=this.slot._colorTransform;if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){if(result.alphaMultiplier!==this._result[0]||result.redMultiplier!==this._result[1]||result.greenMultiplier!==this._result[2]||result.blueMultiplier!==this._result[3]||result.alphaOffset!==this._result[4]||result.redOffset!==this._result[5]||result.greenOffset!==this._result[6]||result.blueOffset!==this._result[7]){var fadeProgress=Math.pow(this._animationState._fadeProgress,4);result.alphaMultiplier+=(this._result[0]-result.alphaMultiplier)*fadeProgress;result.redMultiplier+=(this._result[1]-result.redMultiplier)*fadeProgress;result.greenMultiplier+=(this._result[2]-result.greenMultiplier)*fadeProgress;result.blueMultiplier+=(this._result[3]-result.blueMultiplier)*fadeProgress;result.alphaOffset+=(this._result[4]-result.alphaOffset)*fadeProgress;result.redOffset+=(this._result[5]-result.redOffset)*fadeProgress;result.greenOffset+=(this._result[6]-result.greenOffset)*fadeProgress;result.blueOffset+=(this._result[7]-result.blueOffset)*fadeProgress;this.slot._colorDirty=true;}}else if(this._dirty){this._dirty=false;if(result.alphaMultiplier!==this._result[0]||result.redMultiplier!==this._result[1]||result.greenMultiplier!==this._result[2]||result.blueMultiplier!==this._result[3]||result.alphaOffset!==this._result[4]||result.redOffset!==this._result[5]||result.greenOffset!==this._result[6]||result.blueOffset!==this._result[7]){result.alphaMultiplier=this._result[0];result.redMultiplier=this._result[1];result.greenMultiplier=this._result[2];result.blueMultiplier=this._result[3];result.alphaOffset=this._result[4];result.redOffset=this._result[5];result.greenOffset=this._result[6];result.blueOffset=this._result[7];this.slot._colorDirty=true;}}}};return SlotColorTimelineState;}(dragonBones.SlotTimelineState);dragonBones.SlotColorTimelineState=SlotColorTimelineState;var DeformTimelineState=function(_super){__extends(DeformTimelineState,_super);function DeformTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[];_this._delta=[];_this._result=[];return _this;}DeformTimelineState.toString=function(){return "[class dragonBones.DeformTimelineState]";};DeformTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.vertexOffset=0;this._dirty=false;this._frameFloatOffset=0;this._valueCount=0;this._deformCount=0;this._valueOffset=0;this._current.length=0;this._delta.length=0;this._result.length=0;};DeformTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*this._valueCount;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;if(this._tweenState===2){var nextValueOffset=valueOffset+this._valueCount;if(this._frameIndex===this._frameCount-1){nextValueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}for(var i=0;i<this._valueCount;++i){this._delta[i]=frameFloatArray[nextValueOffset+i]*scale-(this._current[i]=frameFloatArray[valueOffset+i]*scale);}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=frameFloatArray[valueOffset+i]*scale;}}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=0.0;}}};DeformTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this._dirty=true;if(this._tweenState!==2){this._tweenState=0;}for(var i=0;i<this._valueCount;++i){this._result[i]=this._current[i]+this._delta[i]*this._tweenProgress;}};DeformTimelineState.prototype.init=function(armature,animationState,timelineData){_super.prototype.init.call(this,armature,animationState,timelineData);if(this._timelineData!==null){var frameIntOffset=this._animationData.frameIntOffset+this._timelineArray[this._timelineData.offset+3];this.vertexOffset=this._frameIntArray[frameIntOffset+0];if(this.vertexOffset<0){this.vertexOffset+=65536;}this._deformCount=this._frameIntArray[frameIntOffset+1];this._valueCount=this._frameIntArray[frameIntOffset+2];this._valueOffset=this._frameIntArray[frameIntOffset+3];this._frameFloatOffset=this._frameIntArray[frameIntOffset+4]+this._animationData.frameFloatOffset;}else {var deformVertices=this.slot._deformVertices;this._deformCount=deformVertices!==null?deformVertices.vertices.length:0;this._valueCount=this._deformCount;this._valueOffset=0;this._frameFloatOffset=0;}this._current.length=this._valueCount;this._delta.length=this._valueCount;this._result.length=this._valueCount;for(var i=0;i<this._valueCount;++i){this._delta[i]=0.0;}};DeformTimelineState.prototype.fadeOut=function(){this._tweenState=0;this._dirty=false;};DeformTimelineState.prototype.update=function(passedTime){var deformVertices=this.slot._deformVertices;if(deformVertices===null||deformVertices.verticesData===null||deformVertices.verticesData.offset!==this.vertexOffset){return;}_super.prototype.update.call(this,passedTime);if(this._tweenState!==0||this._dirty){var result=deformVertices.vertices;if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){var fadeProgress=Math.pow(this._animationState._fadeProgress,2);for(var i=0;i<this._deformCount;++i){if(i<this._valueOffset){result[i]+=(this._frameFloatArray[this._frameFloatOffset+i]-result[i])*fadeProgress;}else if(i<this._valueOffset+this._valueCount){result[i]+=(this._result[i-this._valueOffset]-result[i])*fadeProgress;}else {result[i]+=(this._frameFloatArray[this._frameFloatOffset+i-this._valueCount]-result[i])*fadeProgress;}}deformVertices.verticesDirty=true;}else if(this._dirty){this._dirty=false;for(var i=0;i<this._deformCount;++i){if(i<this._valueOffset){result[i]=this._frameFloatArray[this._frameFloatOffset+i];}else if(i<this._valueOffset+this._valueCount){result[i]=this._result[i-this._valueOffset];}else {result[i]=this._frameFloatArray[this._frameFloatOffset+i-this._valueCount];}}deformVertices.verticesDirty=true;}}};return DeformTimelineState;}(dragonBones.SlotTimelineState);dragonBones.DeformTimelineState=DeformTimelineState;var IKConstraintTimelineState=function(_super){__extends(IKConstraintTimelineState,_super);function IKConstraintTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraintTimelineState.toString=function(){return "[class dragonBones.IKConstraintTimelineState]";};IKConstraintTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._current=0.0;this._delta=0.0;};IKConstraintTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);var ikConstraint=this.constraint;if(this._timelineData!==null){var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*2;var frameIntArray=this._frameIntArray;var bendPositive=frameIntArray[valueOffset++]!==0;this._current=frameIntArray[valueOffset++]*0.01;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameIntOffset+this._frameValueOffset;}this._delta=frameIntArray[valueOffset+1]*0.01-this._current;}else {this._delta=0.0;}ikConstraint._bendPositive=bendPositive;}else {var ikConstraintData=ikConstraint._constraintData;this._current=ikConstraintData.weight;this._delta=0.0;ikConstraint._bendPositive=ikConstraintData.bendPositive;}ikConstraint.invalidUpdate();};IKConstraintTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);if(this._tweenState!==2){this._tweenState=0;}var ikConstraint=this.constraint;ikConstraint._weight=this._current+this._delta*this._tweenProgress;ikConstraint.invalidUpdate();};return IKConstraintTimelineState;}(dragonBones.ConstraintTimelineState);dragonBones.IKConstraintTimelineState=IKConstraintTimelineState;var AnimationTimelineState=function(_super){__extends(AnimationTimelineState,_super);function AnimationTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._floats=[0.0,0.0,0.0,0.0,0.0,0.0];return _this;}AnimationTimelineState.toString=function(){return "[class dragonBones.AnimationTimelineState]";};AnimationTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.animationState=null;};AnimationTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData===null){return;}var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*2;var frameRateR=1.0/this.animationState._animationData.parent.frameRate;var frameIntArray=this._frameIntArray;this._floats[0]=frameIntArray[valueOffset++]*frameRateR;this._floats[3]=frameIntArray[valueOffset++]*0.01;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameIntOffset+this._frameValueOffset;}this._floats[1]=frameIntArray[valueOffset++]*frameRateR-this._floats[0];this._floats[4]=frameIntArray[valueOffset++]*0.01-this._floats[3];}else {this._floats[1]=0.0;this._floats[4]=0.0;}};AnimationTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);if(this._tweenState!==2){this._tweenState=0;}if(this._floats[0]>=0.0){this._floats[2]=this._floats[0]+this._floats[1]*this._tweenProgress;}this._floats[5]=this._floats[3]+this._floats[4]*this._tweenProgress;};AnimationTimelineState.prototype.blend=function(state){var animationState=this.animationState;var blendWeight=animationState._blendState.blendWeight;if(state===2){animationState.weight+=this._floats[5]*blendWeight;animationState.currentTime+=this._floats[2]*blendWeight;}else {animationState.weight=this._floats[5]*blendWeight;animationState.currentTime=this._floats[2]*blendWeight;}};return AnimationTimelineState;}(dragonBones.TweenTimelineState);dragonBones.AnimationTimelineState=AnimationTimelineState;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var EventObject=function(_super){__extends(EventObject,_super);function EventObject(){return _super!==null&&_super.apply(this,arguments)||this;}EventObject.actionDataToInstance=function(data,instance,armature){if(data.type===0){instance.type=EventObject.FRAME_EVENT;}else {instance.type=data.type===10?EventObject.FRAME_EVENT:EventObject.SOUND_EVENT;}instance.name=data.name;instance.armature=armature;instance.actionData=data;instance.data=data.data;if(data.bone!==null){instance.bone=armature.getBone(data.bone.name);}if(data.slot!==null){instance.slot=armature.getSlot(data.slot.name);}};EventObject.toString=function(){return "[class dragonBones.EventObject]";};EventObject.prototype._onClear=function(){this.time=0.0;this.type="";this.name="";this.armature=null;this.bone=null;this.slot=null;this.animationState=null;this.actionData=null;this.data=null;};EventObject.START="start";EventObject.LOOP_COMPLETE="loopComplete";EventObject.COMPLETE="complete";EventObject.FADE_IN="fadeIn";EventObject.FADE_IN_COMPLETE="fadeInComplete";EventObject.FADE_OUT="fadeOut";EventObject.FADE_OUT_COMPLETE="fadeOutComplete";EventObject.FRAME_EVENT="frameEvent";EventObject.SOUND_EVENT="soundEvent";return EventObject;}(dragonBones.BaseObject);dragonBones.EventObject=EventObject;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var DataParser=function(){function DataParser(){}DataParser._getArmatureType=function(value){switch(value.toLowerCase()){case"stage":return 2;case"armature":return 0;case"movieclip":return 1;default:return 0;}};DataParser._getBoneType=function(value){switch(value.toLowerCase()){case"bone":return 0;case"surface":return 1;default:return 0;}};DataParser._getDisplayType=function(value){switch(value.toLowerCase()){case"image":return 0;case"mesh":return 2;case"armature":return 1;case"boundingbox":return 3;case"path":return 4;default:return 0;}};DataParser._getBoundingBoxType=function(value){switch(value.toLowerCase()){case"rectangle":return 0;case"ellipse":return 1;case"polygon":return 2;default:return 0;}};DataParser._getActionType=function(value){switch(value.toLowerCase()){case"play":return 0;case"frame":return 10;case"sound":return 11;default:return 0;}};DataParser._getBlendMode=function(value){switch(value.toLowerCase()){case"normal":return 0;case"add":return 1;case"alpha":return 2;case"darken":return 3;case"difference":return 4;case"erase":return 5;case"hardlight":return 6;case"invert":return 7;case"layer":return 8;case"lighten":return 9;case"multiply":return 10;case"overlay":return 11;case"screen":return 12;case"subtract":return 13;default:return 0;}};DataParser._getPositionMode=function(value){switch(value.toLocaleLowerCase()){case"percent":return 1;case"fixed":return 0;default:return 1;}};DataParser._getSpacingMode=function(value){switch(value.toLocaleLowerCase()){case"length":return 0;case"percent":return 2;case"fixed":return 1;default:return 0;}};DataParser._getRotateMode=function(value){switch(value.toLocaleLowerCase()){case"tangent":return 0;case"chain":return 1;case"chainscale":return 2;default:return 0;}};DataParser.parseDragonBonesData=function(rawData){console.warn("Deprecated.");if(rawData instanceof ArrayBuffer){return dragonBones.BinaryDataParser.getInstance().parseDragonBonesData(rawData);}else {return dragonBones.ObjectDataParser.getInstance().parseDragonBonesData(rawData);}};DataParser.parseTextureAtlasData=function(rawData,scale){if(scale===void 0){scale=1;}console.warn("已废弃");var textureAtlasData={};var subTextureList=rawData[DataParser.SUB_TEXTURE];for(var i=0,len=subTextureList.length;i<len;i++){var subTextureObject=subTextureList[i];var subTextureName=subTextureObject[DataParser.NAME];var subTextureRegion=new dragonBones.Rectangle();var subTextureFrame=null;subTextureRegion.x=subTextureObject[DataParser.X]/scale;subTextureRegion.y=subTextureObject[DataParser.Y]/scale;subTextureRegion.width=subTextureObject[DataParser.WIDTH]/scale;subTextureRegion.height=subTextureObject[DataParser.HEIGHT]/scale;if(DataParser.FRAME_WIDTH in subTextureObject){subTextureFrame=new dragonBones.Rectangle();subTextureFrame.x=subTextureObject[DataParser.FRAME_X]/scale;subTextureFrame.y=subTextureObject[DataParser.FRAME_Y]/scale;subTextureFrame.width=subTextureObject[DataParser.FRAME_WIDTH]/scale;subTextureFrame.height=subTextureObject[DataParser.FRAME_HEIGHT]/scale;}textureAtlasData[subTextureName]={region:subTextureRegion,frame:subTextureFrame,rotated:false};}return textureAtlasData;};DataParser.DATA_VERSION_2_3="2.3";DataParser.DATA_VERSION_3_0="3.0";DataParser.DATA_VERSION_4_0="4.0";DataParser.DATA_VERSION_4_5="4.5";DataParser.DATA_VERSION_5_0="5.0";DataParser.DATA_VERSION_5_5="5.5";DataParser.DATA_VERSION=DataParser.DATA_VERSION_5_5;DataParser.DATA_VERSIONS=[DataParser.DATA_VERSION_4_0,DataParser.DATA_VERSION_4_5,DataParser.DATA_VERSION_5_0,DataParser.DATA_VERSION_5_5];DataParser.TEXTURE_ATLAS="textureAtlas";DataParser.SUB_TEXTURE="SubTexture";DataParser.FORMAT="format";DataParser.IMAGE_PATH="imagePath";DataParser.WIDTH="width";DataParser.HEIGHT="height";DataParser.ROTATED="rotated";DataParser.FRAME_X="frameX";DataParser.FRAME_Y="frameY";DataParser.FRAME_WIDTH="frameWidth";DataParser.FRAME_HEIGHT="frameHeight";DataParser.DRADON_BONES="dragonBones";DataParser.USER_DATA="userData";DataParser.ARMATURE="armature";DataParser.BONE="bone";DataParser.SURFACE="surface";DataParser.SLOT="slot";DataParser.CONSTRAINT="constraint";DataParser.IK="ik";DataParser.PATH_CONSTRAINT="path";DataParser.SKIN="skin";DataParser.DISPLAY="display";DataParser.ANIMATION="animation";DataParser.Z_ORDER="zOrder";DataParser.FFD="ffd";DataParser.FRAME="frame";DataParser.TRANSLATE_FRAME="translateFrame";DataParser.ROTATE_FRAME="rotateFrame";DataParser.SCALE_FRAME="scaleFrame";DataParser.DISPLAY_FRAME="displayFrame";DataParser.COLOR_FRAME="colorFrame";DataParser.DEFAULT_ACTIONS="defaultActions";DataParser.ACTIONS="actions";DataParser.EVENTS="events";DataParser.INTS="ints";DataParser.FLOATS="floats";DataParser.STRINGS="strings";DataParser.CANVAS="canvas";DataParser.TRANSFORM="transform";DataParser.PIVOT="pivot";DataParser.AABB="aabb";DataParser.COLOR="color";DataParser.VERSION="version";DataParser.COMPATIBLE_VERSION="compatibleVersion";DataParser.FRAME_RATE="frameRate";DataParser.TYPE="type";DataParser.SUB_TYPE="subType";DataParser.NAME="name";DataParser.PARENT="parent";DataParser.TARGET="target";DataParser.STAGE="stage";DataParser.SHARE="share";DataParser.PATH="path";DataParser.LENGTH="length";DataParser.DISPLAY_INDEX="displayIndex";DataParser.BLEND_MODE="blendMode";DataParser.INHERIT_TRANSLATION="inheritTranslation";DataParser.INHERIT_ROTATION="inheritRotation";DataParser.INHERIT_SCALE="inheritScale";DataParser.INHERIT_REFLECTION="inheritReflection";DataParser.INHERIT_ANIMATION="inheritAnimation";DataParser.INHERIT_DEFORM="inheritDeform";DataParser.SEGMENT_X="segmentX";DataParser.SEGMENT_Y="segmentY";DataParser.BEND_POSITIVE="bendPositive";DataParser.CHAIN="chain";DataParser.WEIGHT="weight";DataParser.FADE_IN_TIME="fadeInTime";DataParser.PLAY_TIMES="playTimes";DataParser.SCALE="scale";DataParser.OFFSET="offset";DataParser.POSITION="position";DataParser.DURATION="duration";DataParser.TWEEN_EASING="tweenEasing";DataParser.TWEEN_ROTATE="tweenRotate";DataParser.TWEEN_SCALE="tweenScale";DataParser.CLOCK_WISE="clockwise";DataParser.CURVE="curve";DataParser.SOUND="sound";DataParser.EVENT="event";DataParser.ACTION="action";DataParser.X="x";DataParser.Y="y";DataParser.SKEW_X="skX";DataParser.SKEW_Y="skY";DataParser.SCALE_X="scX";DataParser.SCALE_Y="scY";DataParser.VALUE="value";DataParser.ROTATE="rotate";DataParser.SKEW="skew";DataParser.ALPHA_OFFSET="aO";DataParser.RED_OFFSET="rO";DataParser.GREEN_OFFSET="gO";DataParser.BLUE_OFFSET="bO";DataParser.ALPHA_MULTIPLIER="aM";DataParser.RED_MULTIPLIER="rM";DataParser.GREEN_MULTIPLIER="gM";DataParser.BLUE_MULTIPLIER="bM";DataParser.UVS="uvs";DataParser.VERTICES="vertices";DataParser.TRIANGLES="triangles";DataParser.WEIGHTS="weights";DataParser.SLOT_POSE="slotPose";DataParser.BONE_POSE="bonePose";DataParser.GLUE_WEIGHTS="glueWeights";DataParser.GLUE_MESHES="glueMeshes";DataParser.BONES="bones";DataParser.POSITION_MODE="positionMode";DataParser.SPACING_MODE="spacingMode";DataParser.ROTATE_MODE="rotateMode";DataParser.SPACING="spacing";DataParser.ROTATE_OFFSET="rotateOffset";DataParser.ROTATE_MIX="rotateMix";DataParser.TRANSLATE_MIX="translateMix";DataParser.TARGET_DISPLAY="targetDisplay";DataParser.CLOSED="closed";DataParser.CONSTANT_SPEED="constantSpeed";DataParser.VERTEX_COUNT="vertexCount";DataParser.LENGTHS="lengths";DataParser.GOTO_AND_PLAY="gotoAndPlay";DataParser.DEFAULT_NAME="default";return DataParser;}();dragonBones.DataParser=DataParser;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var ObjectDataParser=function(_super){__extends(ObjectDataParser,_super);function ObjectDataParser(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._rawTextureAtlasIndex=0;_this._rawBones=[];_this._data=null;_this._armature=null;_this._bone=null;_this._surface=null;_this._slot=null;_this._skin=null;_this._mesh=null;_this._animation=null;_this._timeline=null;_this._rawTextureAtlases=null;_this._defaultColorOffset=-1;_this._prevClockwise=0;_this._prevRotation=0.0;_this._helpMatrixA=new dragonBones.Matrix();_this._helpMatrixB=new dragonBones.Matrix();_this._helpTransform=new dragonBones.Transform();_this._helpColorTransform=new dragonBones.ColorTransform();_this._helpPoint=new dragonBones.Point();_this._helpArray=[];_this._intArray=[];_this._floatArray=[];_this._frameIntArray=[];_this._frameFloatArray=[];_this._frameArray=[];_this._timelineArray=[];_this._cacheRawMeshes=[];_this._cacheMeshes=[];_this._actionFrames=[];_this._weightSlotPose={};_this._weightBonePoses={};_this._cacheBones={};_this._slotChildActions={};return _this;}ObjectDataParser._getBoolean=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];var type=typeof value;if(type==="boolean"){return value;}else if(type==="string"){switch(value){case"0":case"NaN":case"":case"false":case"null":case"undefined":return false;default:return true;}}else {return !!value;}}return defaultValue;};ObjectDataParser._getNumber=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];if(value===null||value==="NaN"){return defaultValue;}return +value||0;}return defaultValue;};ObjectDataParser._getString=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];var type=typeof value;if(type==="string"){if(dragonBones.DragonBones.webAssembly){for(var i=0,l=value.length;i<l;++i){if(value.charCodeAt(i)>255){return encodeURI(value);}}}return value;}return String(value);}return defaultValue;};ObjectDataParser.prototype._getCurvePoint=function(x1,y1,x2,y2,x3,y3,x4,y4,t,result){var l_t=1.0-t;var powA=l_t*l_t;var powB=t*t;var kA=l_t*powA;var kB=3.0*t*powA;var kC=3.0*l_t*powB;var kD=t*powB;result.x=kA*x1+kB*x2+kC*x3+kD*x4;result.y=kA*y1+kB*y2+kC*y3+kD*y4;};ObjectDataParser.prototype._samplingEasingCurve=function(curve,samples){var curveCount=curve.length;var stepIndex=-2;for(var i=0,l=samples.length;i<l;++i){var t=(i+1)/(l+1);while((stepIndex+6<curveCount?curve[stepIndex+6]:1)<t){stepIndex+=6;}var isInCurve=stepIndex>=0&&stepIndex+6<curveCount;var x1=isInCurve?curve[stepIndex]:0.0;var y1=isInCurve?curve[stepIndex+1]:0.0;var x2=curve[stepIndex+2];var y2=curve[stepIndex+3];var x3=curve[stepIndex+4];var y3=curve[stepIndex+5];var x4=isInCurve?curve[stepIndex+6]:1.0;var y4=isInCurve?curve[stepIndex+7]:1.0;var lower=0.0;var higher=1.0;while(higher-lower>0.0001){var percentage=(higher+lower)*0.5;this._getCurvePoint(x1,y1,x2,y2,x3,y3,x4,y4,percentage,this._helpPoint);if(t-this._helpPoint.x>0.0){lower=percentage;}else {higher=percentage;}}samples[i]=this._helpPoint.y;}};ObjectDataParser.prototype._parseActionDataInFrame=function(rawData,frameStart,bone,slot){if(dragonBones.DataParser.EVENT in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.EVENT],frameStart,10,bone,slot);}if(dragonBones.DataParser.SOUND in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.SOUND],frameStart,11,bone,slot);}if(dragonBones.DataParser.ACTION in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.ACTION],frameStart,0,bone,slot);}if(dragonBones.DataParser.EVENTS in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.EVENTS],frameStart,10,bone,slot);}if(dragonBones.DataParser.ACTIONS in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.ACTIONS],frameStart,0,bone,slot);}};ObjectDataParser.prototype._mergeActionFrame=function(rawData,frameStart,type,bone,slot){var actionOffset=dragonBones.DragonBones.webAssembly?this._armature.actions.size():this._armature.actions.length;var actions=this._parseActionData(rawData,type,bone,slot);var frameIndex=0;var frame=null;for(var _i=0,actions_2=actions;_i<actions_2.length;_i++){var action=actions_2[_i];this._armature.addAction(action,false);}if(this._actionFrames.length===0){frame=new ActionFrame();frame.frameStart=0;this._actionFrames.push(frame);frame=null;}for(var _a=0,_b=this._actionFrames;_a<_b.length;_a++){var eachFrame=_b[_a];if(eachFrame.frameStart===frameStart){frame=eachFrame;break;}else if(eachFrame.frameStart>frameStart){break;}frameIndex++;}if(frame===null){frame=new ActionFrame();frame.frameStart=frameStart;this._actionFrames.splice(frameIndex+1,0,frame);}for(var i=0;i<actions.length;++i){frame.actions.push(actionOffset+i);}};ObjectDataParser.prototype._parseArmature=function(rawData,scale){var armature=dragonBones.BaseObject.borrowObject(dragonBones.ArmatureData);armature.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");armature.frameRate=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FRAME_RATE,this._data.frameRate);armature.scale=scale;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){armature.type=dragonBones.DataParser._getArmatureType(rawData[dragonBones.DataParser.TYPE]);}else {armature.type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,0);}if(armature.frameRate===0){armature.frameRate=24;}this._armature=armature;if(dragonBones.DataParser.CANVAS in rawData){var rawCanvas=rawData[dragonBones.DataParser.CANVAS];var canvas=dragonBones.BaseObject.borrowObject(dragonBones.CanvasData);if(dragonBones.DataParser.COLOR in rawCanvas){canvas.hasBackground=true;}else {canvas.hasBackground=false;}canvas.color=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.COLOR,0);canvas.x=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.X,0)*armature.scale;canvas.y=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.Y,0)*armature.scale;canvas.width=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.WIDTH,0)*armature.scale;canvas.height=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.HEIGHT,0)*armature.scale;armature.canvas=canvas;}if(dragonBones.DataParser.AABB in rawData){var rawAABB=rawData[dragonBones.DataParser.AABB];armature.aabb.x=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.X,0.0)*armature.scale;armature.aabb.y=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.Y,0.0)*armature.scale;armature.aabb.width=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.WIDTH,0.0)*armature.scale;armature.aabb.height=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.HEIGHT,0.0)*armature.scale;}if(dragonBones.DataParser.BONE in rawData){var rawBones=rawData[dragonBones.DataParser.BONE];for(var _i=0,rawBones_1=rawBones;_i<rawBones_1.length;_i++){var rawBone=rawBones_1[_i];var parentName=ObjectDataParser._getString(rawBone,dragonBones.DataParser.PARENT,"");var bone=this._parseBone(rawBone);if(parentName.length>0){var parent_1=armature.getBone(parentName);if(parent_1!==null){bone.parent=parent_1;}else {if(!(parentName in this._cacheBones)){this._cacheBones[parentName]=[];}this._cacheBones[parentName].push(bone);}}if(bone.name in this._cacheBones){for(var _a=0,_b=this._cacheBones[bone.name];_a<_b.length;_a++){var child=_b[_a];child.parent=bone;}delete this._cacheBones[bone.name];}armature.addBone(bone);this._rawBones.push(bone);}}if(dragonBones.DataParser.IK in rawData){var rawIKS=rawData[dragonBones.DataParser.IK];for(var _c=0,rawIKS_1=rawIKS;_c<rawIKS_1.length;_c++){var rawIK=rawIKS_1[_c];var constraint=this._parseIKConstraint(rawIK);if(constraint){armature.addConstraint(constraint);}}}armature.sortBones();if(dragonBones.DataParser.SLOT in rawData){var zOrder=0;var rawSlots=rawData[dragonBones.DataParser.SLOT];for(var _d=0,rawSlots_1=rawSlots;_d<rawSlots_1.length;_d++){var rawSlot=rawSlots_1[_d];armature.addSlot(this._parseSlot(rawSlot,zOrder++));}}if(dragonBones.DataParser.SKIN in rawData){var rawSkins=rawData[dragonBones.DataParser.SKIN];for(var _e=0,rawSkins_1=rawSkins;_e<rawSkins_1.length;_e++){var rawSkin=rawSkins_1[_e];armature.addSkin(this._parseSkin(rawSkin));}}if(dragonBones.DataParser.PATH_CONSTRAINT in rawData){var rawPaths=rawData[dragonBones.DataParser.PATH_CONSTRAINT];for(var _f=0,rawPaths_1=rawPaths;_f<rawPaths_1.length;_f++){var rawPath=rawPaths_1[_f];var constraint=this._parsePathConstraint(rawPath);if(constraint){armature.addConstraint(constraint);}}}for(var i=0,l=this._cacheRawMeshes.length;i<l;++i){var rawMeshData=this._cacheRawMeshes[i];if(!(dragonBones.DataParser.GLUE_WEIGHTS in rawMeshData)||!(dragonBones.DataParser.GLUE_MESHES in rawMeshData)){continue;}this._parseMeshGlue(rawMeshData,this._cacheMeshes[i]);}for(var i=0,l=this._cacheRawMeshes.length;i<l;++i){var rawData_1=this._cacheRawMeshes[i];var shareName=ObjectDataParser._getString(rawData_1,dragonBones.DataParser.SHARE,"");if(shareName.length===0){continue;}var skinName=ObjectDataParser._getString(rawData_1,dragonBones.DataParser.SKIN,dragonBones.DataParser.DEFAULT_NAME);if(skinName.length===0){skinName=dragonBones.DataParser.DEFAULT_NAME;}var shareMesh=armature.getMesh(skinName,"",shareName);if(shareMesh===null){continue;}var mesh=this._cacheMeshes[i];mesh.vertices.shareFrom(shareMesh.vertices);}if(dragonBones.DataParser.ANIMATION in rawData){var rawAnimations=rawData[dragonBones.DataParser.ANIMATION];for(var _g=0,rawAnimations_1=rawAnimations;_g<rawAnimations_1.length;_g++){var rawAnimation=rawAnimations_1[_g];var animation=this._parseAnimation(rawAnimation);armature.addAnimation(animation);}}if(dragonBones.DataParser.DEFAULT_ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.DEFAULT_ACTIONS],0,null,null);for(var _h=0,actions_3=actions;_h<actions_3.length;_h++){var action=actions_3[_h];armature.addAction(action,true);if(action.type===0){var animation=armature.getAnimation(action.name);if(animation!==null){armature.defaultAnimation=animation;}}}}if(dragonBones.DataParser.ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);for(var _j=0,actions_4=actions;_j<actions_4.length;_j++){var action=actions_4[_j];armature.addAction(action,false);}}this._rawBones.length=0;this._cacheRawMeshes.length=0;this._cacheMeshes.length=0;this._armature=null;for(var k in this._weightSlotPose){delete this._weightSlotPose[k];}for(var k in this._weightBonePoses){delete this._weightBonePoses[k];}for(var k in this._cacheBones){delete this._cacheBones[k];}for(var k in this._slotChildActions){delete this._slotChildActions[k];}return armature;};ObjectDataParser.prototype._parseBone=function(rawData){var type=0;var scale=this._armature.scale;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){type=dragonBones.DataParser._getBoneType(rawData[dragonBones.DataParser.TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,0);}if(type===0){var bone=dragonBones.BaseObject.borrowObject(dragonBones.BoneData);bone.inheritTranslation=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_TRANSLATION,true);bone.inheritRotation=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_ROTATION,true);bone.inheritScale=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_SCALE,true);bone.inheritReflection=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_REFLECTION,true);bone.length=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.LENGTH,0)*scale;bone.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");if(dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],bone.transform,scale);}return bone;}var surface=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceData);surface.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");surface.segmentX=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SEGMENT_X,0);surface.segmentY=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SEGMENT_Y,0);surface.vertices.length=(surface.segmentX+1)*(surface.segmentY+1)*2;if(dragonBones.DataParser.VERTICES in rawData){var rawVertices=rawData[dragonBones.DataParser.VERTICES];for(var i=0,l=surface.vertices.length;i<l;++i){if(i<rawVertices.length){surface.vertices[i]=rawVertices[i]*scale;}else {surface.vertices[i]=0.0;}}}return surface;};ObjectDataParser.prototype._parseIKConstraint=function(rawData){var bone=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.BONE,""));if(bone===null){return null;}var target=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET,""));if(target===null){return null;}var constraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintData);constraint.scaleEnabled=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.SCALE,false);constraint.bendPositive=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.BEND_POSITIVE,true);constraint.weight=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0);constraint.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");constraint.type=0;constraint.target=target;var chain=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.CHAIN,0);if(chain>0&&bone.parent!==null){constraint.root=bone.parent;constraint.bone=bone;}else {constraint.root=bone;constraint.bone=null;}return constraint;};ObjectDataParser.prototype._parsePathConstraint=function(rawData){var target=this._armature.getSlot(ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET,""));if(target===null){return null;}var defaultSkin=this._armature.defaultSkin;if(defaultSkin===null){return null;}var targetDisplay=defaultSkin.getDisplay(target.name,ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET_DISPLAY,target.name));if(targetDisplay===null||!(targetDisplay instanceof dragonBones.PathDisplayData)){return null;}var bones=rawData[dragonBones.DataParser.BONES];if(bones===null||bones.length===0){return null;}var constraint=dragonBones.BaseObject.borrowObject(dragonBones.PathConstraintData);constraint.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");constraint.type=1;constraint.pathSlot=target;constraint.pathDisplayData=targetDisplay;constraint.target=target.parent;constraint.positionMode=dragonBones.DataParser._getPositionMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.POSITION_MODE,""));constraint.spacingMode=dragonBones.DataParser._getSpacingMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.SPACING_MODE,""));constraint.rotateMode=dragonBones.DataParser._getRotateMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.ROTATE_MODE,""));constraint.position=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.POSITION,0);constraint.spacing=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SPACING,0);constraint.rotateOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE_OFFSET,0);constraint.rotateMix=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE_MIX,1);constraint.translateMix=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TRANSLATE_MIX,1);for(var _i=0,bones_3=bones;_i<bones_3.length;_i++){var boneName=bones_3[_i];var bone=this._armature.getBone(boneName);if(bone!==null){constraint.AddBone(bone);if(constraint.root===null){constraint.root=bone;}}}return constraint;};ObjectDataParser.prototype._parseSlot=function(rawData,zOrder){var slot=dragonBones.BaseObject.borrowObject(dragonBones.SlotData);slot.displayIndex=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DISPLAY_INDEX,0);slot.zOrder=zOrder;slot.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");slot.parent=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.PARENT,""));if(dragonBones.DataParser.BLEND_MODE in rawData&&typeof rawData[dragonBones.DataParser.BLEND_MODE]==="string"){slot.blendMode=dragonBones.DataParser._getBlendMode(rawData[dragonBones.DataParser.BLEND_MODE]);}else {slot.blendMode=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLEND_MODE,0);}if(dragonBones.DataParser.COLOR in rawData){slot.color=dragonBones.SlotData.createColor();this._parseColorTransform(rawData[dragonBones.DataParser.COLOR],slot.color);}else {slot.color=dragonBones.SlotData.DEFAULT_COLOR;}if(dragonBones.DataParser.ACTIONS in rawData){this._slotChildActions[slot.name]=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);}return slot;};ObjectDataParser.prototype._parseSkin=function(rawData){var skin=dragonBones.BaseObject.borrowObject(dragonBones.SkinData);skin.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(skin.name.length===0){skin.name=dragonBones.DataParser.DEFAULT_NAME;}if(dragonBones.DataParser.SLOT in rawData){var rawSlots=rawData[dragonBones.DataParser.SLOT];this._skin=skin;for(var _i=0,rawSlots_2=rawSlots;_i<rawSlots_2.length;_i++){var rawSlot=rawSlots_2[_i];var slotName=ObjectDataParser._getString(rawSlot,dragonBones.DataParser.NAME,"");var slot=this._armature.getSlot(slotName);if(slot!==null){this._slot=slot;if(dragonBones.DataParser.DISPLAY in rawSlot){var rawDisplays=rawSlot[dragonBones.DataParser.DISPLAY];for(var _a=0,rawDisplays_1=rawDisplays;_a<rawDisplays_1.length;_a++){var rawDisplay=rawDisplays_1[_a];if(rawDisplay){skin.addDisplay(slotName,this._parseDisplay(rawDisplay));}else {skin.addDisplay(slotName,null);}}}this._slot=null;}}this._skin=null;}return skin;};ObjectDataParser.prototype._parseDisplay=function(rawData){var name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");var path=ObjectDataParser._getString(rawData,dragonBones.DataParser.PATH,"");var type=0;var display=null;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){type=dragonBones.DataParser._getDisplayType(rawData[dragonBones.DataParser.TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,type);}switch(type){case 0:var imageDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.ImageDisplayData);imageDisplay.name=name;imageDisplay.path=path.length>0?path:name;this._parsePivot(rawData,imageDisplay);break;case 1:var armatureDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.ArmatureDisplayData);armatureDisplay.name=name;armatureDisplay.path=path.length>0?path:name;armatureDisplay.inheritAnimation=true;if(dragonBones.DataParser.ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);for(var _i=0,actions_5=actions;_i<actions_5.length;_i++){var action=actions_5[_i];armatureDisplay.addAction(action);}}else if(this._slot.name in this._slotChildActions){var displays=this._skin.getDisplays(this._slot.name);if(displays===null?this._slot.displayIndex===0:this._slot.displayIndex===displays.length){for(var _a=0,_b=this._slotChildActions[this._slot.name];_a<_b.length;_a++){var action=_b[_a];armatureDisplay.addAction(action);}delete this._slotChildActions[this._slot.name];}}break;case 2:var meshDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.MeshDisplayData);meshDisplay.vertices.inheritDeform=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_DEFORM,true);meshDisplay.name=name;meshDisplay.path=path.length>0?path:name;meshDisplay.vertices.data=this._data;if(dragonBones.DataParser.SHARE in rawData){this._cacheRawMeshes.push(rawData);this._cacheMeshes.push(meshDisplay);}else {this._parseMesh(rawData,meshDisplay);}if(dragonBones.DataParser.GLUE_WEIGHTS in rawData&&dragonBones.DataParser.GLUE_MESHES in rawData){this._cacheRawMeshes.push(rawData);this._cacheMeshes.push(meshDisplay);}break;case 3:var boundingBox=this._parseBoundingBox(rawData);if(boundingBox!==null){var boundingBoxDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.BoundingBoxDisplayData);boundingBoxDisplay.name=name;boundingBoxDisplay.path=path.length>0?path:name;boundingBoxDisplay.boundingBox=boundingBox;}break;case 4:var rawCurveLengths=rawData[dragonBones.DataParser.LENGTHS];var pathDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.PathDisplayData);pathDisplay.closed=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.CLOSED,false);pathDisplay.constantSpeed=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.CONSTANT_SPEED,false);pathDisplay.name=name;pathDisplay.path=path.length>0?path:name;pathDisplay.vertices.data=this._data;pathDisplay.curveLengths.length=rawCurveLengths.length;for(var i=0,l=rawCurveLengths.length;i<l;++i){pathDisplay.curveLengths[i]=rawCurveLengths[i];}this._parsePath(rawData,pathDisplay);break;}if(display!==null&&dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],display.transform,this._armature.scale);}return display;};ObjectDataParser.prototype._parsePath=function(rawData,display){var rawVertices=rawData[dragonBones.DataParser.VERTICES];var vertexCount=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VERTEX_COUNT,0);var vertexOffset=this._floatArray.length;var pathOffset=this._intArray.length;display.vertices.offset=pathOffset;this._intArray.length+=1+1;this._intArray[pathOffset+0]=vertexCount;this._intArray[pathOffset+2]=vertexOffset;if(!(dragonBones.DataParser.WEIGHTS in rawData)){this._floatArray.length+=rawVertices.length;for(var i=0,l=rawVertices.length;i<l;++i){this._floatArray[vertexOffset+i]=rawVertices[i];}}else {var rawWeights=rawData[dragonBones.DataParser.WEIGHTS];var rawBones=rawData[dragonBones.DataParser.BONES];var weightBoneCount=rawBones.length;var weightCount=Math.floor(rawWeights.length-vertexCount)/2;var weightOffset=this._intArray.length;var floatOffset=this._floatArray.length;var sortedBones=this._armature.sortedBones;var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);weight.count=weightCount;weight.offset=weightOffset;this._intArray.length+=1+1+weightBoneCount+vertexCount+weightCount;this._intArray[weightOffset+0]=weightBoneCount;this._intArray[weightOffset+1]=floatOffset;for(var i=0;i<weightBoneCount;i++){var rawBoneIndex=rawBones[i];var bone=this._rawBones[rawBoneIndex];weight.addBone(bone);this._intArray[weightOffset+2+i]=sortedBones.indexOf(bone);}this._floatArray.length+=weightCount*3;for(var i=0,iW=0,iV=0,iB=weightOffset+2+weightBoneCount,iF=floatOffset;i<weightCount;i++){var boneCount=rawWeights[iW++];this._intArray[iB++]=boneCount;for(var j=0;j<boneCount;j++){var boneIndex=rawWeights[iW++];var boneWeight=rawWeights[iW++];var x=rawVertices[iV++];var y=rawVertices[iV++];this._intArray[iB++]=rawBones.indexOf(boneIndex);this._floatArray[iF++]=boneWeight;this._floatArray[iF++]=x;this._floatArray[iF++]=y;}}display.vertices.weight=weight;}};ObjectDataParser.prototype._parsePivot=function(rawData,display){if(dragonBones.DataParser.PIVOT in rawData){var rawPivot=rawData[dragonBones.DataParser.PIVOT];display.pivot.x=ObjectDataParser._getNumber(rawPivot,dragonBones.DataParser.X,0.0);display.pivot.y=ObjectDataParser._getNumber(rawPivot,dragonBones.DataParser.Y,0.0);}else {display.pivot.x=0.5;display.pivot.y=0.5;}};ObjectDataParser.prototype._parseMesh=function(rawData,mesh){var rawVertices=rawData[dragonBones.DataParser.VERTICES];var rawUVs=rawData[dragonBones.DataParser.UVS];var rawTriangles=rawData[dragonBones.DataParser.TRIANGLES];var vertexCount=Math.floor(rawVertices.length/2);var triangleCount=Math.floor(rawTriangles.length/3);var vertexOffset=this._floatArray.length;var uvOffset=vertexOffset+vertexCount*2;var meshOffset=this._intArray.length;var meshName=this._skin.name+"_"+this._slot.name+"_"+mesh.name;mesh.vertices.offset=meshOffset;this._intArray.length+=1+1+1+1+triangleCount*3;this._intArray[meshOffset+0]=vertexCount;this._intArray[meshOffset+1]=triangleCount;this._intArray[meshOffset+2]=vertexOffset;for(var i=0,l=triangleCount*3;i<l;++i){this._intArray[meshOffset+4+i]=rawTriangles[i];}this._floatArray.length+=vertexCount*2+vertexCount*2;for(var i=0,l=vertexCount*2;i<l;++i){this._floatArray[vertexOffset+i]=rawVertices[i];this._floatArray[uvOffset+i]=rawUVs[i];}if(dragonBones.DataParser.WEIGHTS in rawData){var rawWeights=rawData[dragonBones.DataParser.WEIGHTS];var rawSlotPose=rawData[dragonBones.DataParser.SLOT_POSE];var rawBonePoses=rawData[dragonBones.DataParser.BONE_POSE];var sortedBones=this._armature.sortedBones;var weightBoneIndices=new Array();var weightBoneCount=Math.floor(rawBonePoses.length/7);var floatOffset=this._floatArray.length;var weightCount=Math.floor(rawWeights.length-vertexCount)/2;var weightOffset=this._intArray.length;var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);weight.count=weightCount;weight.offset=weightOffset;weightBoneIndices.length=weightBoneCount;this._intArray.length+=1+1+weightBoneCount+vertexCount+weightCount;this._intArray[weightOffset+1]=floatOffset;for(var i=0;i<weightBoneCount;++i){var rawBoneIndex=rawBonePoses[i*7];var bone=this._rawBones[rawBoneIndex];weight.addBone(bone);weightBoneIndices[i]=rawBoneIndex;this._intArray[weightOffset+2+i]=sortedBones.indexOf(bone);}this._floatArray.length+=weightCount*3;this._helpMatrixA.copyFromArray(rawSlotPose,0);for(var i=0,iW=0,iB=weightOffset+2+weightBoneCount,iV=floatOffset;i<vertexCount;++i){var iD=i*2;var vertexBoneCount=this._intArray[iB++]=rawWeights[iW++];var x=this._floatArray[vertexOffset+iD];var y=this._floatArray[vertexOffset+iD+1];this._helpMatrixA.transformPoint(x,y,this._helpPoint);x=this._helpPoint.x;y=this._helpPoint.y;for(var j=0;j<vertexBoneCount;++j){var rawBoneIndex=rawWeights[iW++];var boneIndex=weightBoneIndices.indexOf(rawBoneIndex);this._helpMatrixB.copyFromArray(rawBonePoses,boneIndex*7+1);this._helpMatrixB.invert();this._helpMatrixB.transformPoint(x,y,this._helpPoint);this._intArray[iB++]=boneIndex;this._floatArray[iV++]=rawWeights[iW++];this._floatArray[iV++]=this._helpPoint.x;this._floatArray[iV++]=this._helpPoint.y;}}mesh.vertices.weight=weight;this._weightSlotPose[meshName]=rawSlotPose;this._weightBonePoses[meshName]=rawBonePoses;}};ObjectDataParser.prototype._parseMeshGlue=function(rawData,mesh){};ObjectDataParser.prototype._parseBoundingBox=function(rawData){var boundingBox=null;var type=0;if(dragonBones.DataParser.SUB_TYPE in rawData&&typeof rawData[dragonBones.DataParser.SUB_TYPE]==="string"){type=dragonBones.DataParser._getBoundingBoxType(rawData[dragonBones.DataParser.SUB_TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SUB_TYPE,type);}switch(type){case 0:boundingBox=dragonBones.BaseObject.borrowObject(dragonBones.RectangleBoundingBoxData);break;case 1:boundingBox=dragonBones.BaseObject.borrowObject(dragonBones.EllipseBoundingBoxData);break;case 2:boundingBox=this._parsePolygonBoundingBox(rawData);break;}if(boundingBox!==null){boundingBox.color=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.COLOR,0x000000);if(boundingBox.type===0||boundingBox.type===1){boundingBox.width=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WIDTH,0.0);boundingBox.height=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.HEIGHT,0.0);}}return boundingBox;};ObjectDataParser.prototype._parsePolygonBoundingBox=function(rawData){var polygonBoundingBox=dragonBones.BaseObject.borrowObject(dragonBones.PolygonBoundingBoxData);if(dragonBones.DataParser.VERTICES in rawData){var scale=this._armature.scale;var rawVertices=rawData[dragonBones.DataParser.VERTICES];var vertices=polygonBoundingBox.vertices;if(dragonBones.DragonBones.webAssembly){vertices.resize(rawVertices.length,0.0);}else {vertices.length=rawVertices.length;}for(var i=0,l=rawVertices.length;i<l;i+=2){var x=rawVertices[i]*scale;var y=rawVertices[i+1]*scale;if(dragonBones.DragonBones.webAssembly){vertices.set(i,x);vertices.set(i+1,y);}else {vertices[i]=x;vertices[i+1]=y;}if(i===0){polygonBoundingBox.x=x;polygonBoundingBox.y=y;polygonBoundingBox.width=x;polygonBoundingBox.height=y;}else {if(x<polygonBoundingBox.x){polygonBoundingBox.x=x;}else if(x>polygonBoundingBox.width){polygonBoundingBox.width=x;}if(y<polygonBoundingBox.y){polygonBoundingBox.y=y;}else if(y>polygonBoundingBox.height){polygonBoundingBox.height=y;}}}polygonBoundingBox.width-=polygonBoundingBox.x;polygonBoundingBox.height-=polygonBoundingBox.y;}else {console.warn("Data error.\n Please reexport DragonBones Data to fixed the bug.");}return polygonBoundingBox;};ObjectDataParser.prototype._parseAnimation=function(rawData){var animation=dragonBones.BaseObject.borrowObject(dragonBones.AnimationData);animation.frameCount=Math.max(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DURATION,1),1);animation.playTimes=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.PLAY_TIMES,1);animation.duration=animation.frameCount/this._armature.frameRate;animation.fadeInTime=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FADE_IN_TIME,0.0);animation.scale=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0);animation.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(animation.name.length===0){animation.name=dragonBones.DataParser.DEFAULT_NAME;}animation.frameIntOffset=this._frameIntArray.length;animation.frameFloatOffset=this._frameFloatArray.length;animation.frameOffset=this._frameArray.length;this._animation=animation;if(dragonBones.DataParser.FRAME in rawData){var rawFrames=rawData[dragonBones.DataParser.FRAME];var keyFrameCount=rawFrames.length;if(keyFrameCount>0){for(var i=0,frameStart=0;i<keyFrameCount;++i){var rawFrame=rawFrames[i];this._parseActionDataInFrame(rawFrame,frameStart,null,null);frameStart+=ObjectDataParser._getNumber(rawFrame,dragonBones.DataParser.DURATION,1);}}}if(dragonBones.DataParser.Z_ORDER in rawData){this._animation.zOrderTimeline=this._parseTimeline(rawData[dragonBones.DataParser.Z_ORDER],null,dragonBones.DataParser.FRAME,1,false,false,0,this._parseZOrderFrame);}if(dragonBones.DataParser.BONE in rawData){var rawTimelines=rawData[dragonBones.DataParser.BONE];for(var _i=0,rawTimelines_1=rawTimelines;_i<rawTimelines_1.length;_i++){var rawTimeline=rawTimelines_1[_i];this._parseBoneTimeline(rawTimeline);}}if(dragonBones.DataParser.SURFACE in rawData){var rawTimelines=rawData[dragonBones.DataParser.SURFACE];for(var _a=0,rawTimelines_2=rawTimelines;_a<rawTimelines_2.length;_a++){var rawTimeline=rawTimelines_2[_a];var surfaceName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");this._surface=this._armature.getBone(surfaceName);if(this._surface===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,50,false,true,0,this._parseSurfaceFrame);if(timeline!==null){this._animation.addSurfaceTimeline(this._surface,timeline);}this._surface=null;}}if(dragonBones.DataParser.SLOT in rawData){var rawTimelines=rawData[dragonBones.DataParser.SLOT];for(var _b=0,rawTimelines_3=rawTimelines;_b<rawTimelines_3.length;_b++){var rawTimeline=rawTimelines_3[_b];this._parseSlotTimeline(rawTimeline);}}if(dragonBones.DataParser.FFD in rawData){var rawTimelines=rawData[dragonBones.DataParser.FFD];for(var _c=0,rawTimelines_4=rawTimelines;_c<rawTimelines_4.length;_c++){var rawTimeline=rawTimelines_4[_c];var skinName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.SKIN,dragonBones.DataParser.DEFAULT_NAME);var slotName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.SLOT,"");var displayName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");if(skinName.length===0){skinName=dragonBones.DataParser.DEFAULT_NAME;}this._slot=this._armature.getSlot(slotName);this._mesh=this._armature.getMesh(skinName,slotName,displayName);if(this._slot===null||this._mesh===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,22,false,true,0,this._parseSlotFFDFrame);if(timeline!==null){this._animation.addSlotTimeline(this._slot,timeline);}this._slot=null;this._mesh=null;}}if(dragonBones.DataParser.IK in rawData){var rawTimelines=rawData[dragonBones.DataParser.IK];for(var _d=0,rawTimelines_5=rawTimelines;_d<rawTimelines_5.length;_d++){var rawTimeline=rawTimelines_5[_d];var constraintName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");var constraint=this._armature.getConstraint(constraintName);if(constraint===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,30,true,false,2,this._parseIKConstraintFrame);if(timeline!==null){this._animation.addConstraintTimeline(constraint,timeline);}}}if(dragonBones.DataParser.ANIMATION in rawData){var rawTimelines=rawData[dragonBones.DataParser.ANIMATION];for(var _e=0,rawTimelines_6=rawTimelines;_e<rawTimelines_6.length;_e++){var rawTimeline=rawTimelines_6[_e];var animationName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,40,true,false,2,this._parseAnimationFrame);if(timeline!==null){this._animation.addAnimationTimeline(animationName,timeline);}}}if(this._actionFrames.length>0){this._animation.actionTimeline=this._parseTimeline(null,this._actionFrames,"",0,false,false,0,this._parseActionFrame);this._actionFrames.length=0;}this._animation=null;return animation;};ObjectDataParser.prototype._parseTimeline=function(rawData,rawFrames,framesKey,type,addIntOffset,addFloatOffset,frameValueCount,frameParser){if(rawData!==null&&framesKey.length>0&&framesKey in rawData){rawFrames=rawData[framesKey];}if(rawFrames===null){return null;}var keyFrameCount=rawFrames.length;if(keyFrameCount===0){return null;}var frameIntArrayLength=this._frameIntArray.length;var frameFloatArrayLength=this._frameFloatArray.length;var timeline=dragonBones.BaseObject.borrowObject(dragonBones.TimelineData);var timelineOffset=this._timelineArray.length;this._timelineArray.length+=1+1+1+1+1+keyFrameCount;if(rawData!==null){this._timelineArray[timelineOffset+0]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0)*100);this._timelineArray[timelineOffset+1]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0.0)*100);}else {this._timelineArray[timelineOffset+0]=100;this._timelineArray[timelineOffset+1]=0;}this._timelineArray[timelineOffset+2]=keyFrameCount;this._timelineArray[timelineOffset+3]=frameValueCount;if(addIntOffset){this._timelineArray[timelineOffset+4]=frameIntArrayLength-this._animation.frameIntOffset;}else if(addFloatOffset){this._timelineArray[timelineOffset+4]=frameFloatArrayLength-this._animation.frameFloatOffset;}else {this._timelineArray[timelineOffset+4]=0;}this._timeline=timeline;timeline.type=type;timeline.offset=timelineOffset;if(keyFrameCount===1){timeline.frameIndicesOffset=-1;this._timelineArray[timelineOffset+5+0]=frameParser.call(this,rawFrames[0],0,0)-this._animation.frameOffset;}else {var totalFrameCount=this._animation.frameCount+1;var frameIndices=this._data.frameIndices;var frameIndicesOffset=0;if(dragonBones.DragonBones.webAssembly){frameIndicesOffset=frameIndices.size();frameIndices.resize(frameIndicesOffset+totalFrameCount,0);}else {frameIndicesOffset=frameIndices.length;frameIndices.length+=totalFrameCount;}timeline.frameIndicesOffset=frameIndicesOffset;for(var i=0,iK=0,frameStart=0,frameCount=0;i<totalFrameCount;++i){if(frameStart+frameCount<=i&&iK<keyFrameCount){var rawFrame=rawFrames[iK];frameStart=i;if(iK===keyFrameCount-1){frameCount=this._animation.frameCount-frameStart;}else {if(rawFrame instanceof ActionFrame){frameCount=this._actionFrames[iK+1].frameStart-frameStart;}else {frameCount=ObjectDataParser._getNumber(rawFrame,dragonBones.DataParser.DURATION,1);}}this._timelineArray[timelineOffset+5+iK]=frameParser.call(this,rawFrame,frameStart,frameCount)-this._animation.frameOffset;iK++;}if(dragonBones.DragonBones.webAssembly){frameIndices.set(frameIndicesOffset+i,iK-1);}else {frameIndices[frameIndicesOffset+i]=iK-1;}}}this._timeline=null;return timeline;};ObjectDataParser.prototype._parseBoneTimeline=function(rawData){var bone=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,""));if(bone===null){return;}this._bone=bone;this._slot=this._armature.getSlot(this._bone.name);if(dragonBones.DataParser.TRANSLATE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.TRANSLATE_FRAME,11,false,true,2,this._parseBoneTranslateFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.ROTATE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.ROTATE_FRAME,12,false,true,2,this._parseBoneRotateFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.SCALE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.SCALE_FRAME,13,false,true,2,this._parseBoneScaleFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,10,false,true,6,this._parseBoneAllFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}this._bone=null;this._slot=null;};ObjectDataParser.prototype._parseSlotTimeline=function(rawData){var slot=this._armature.getSlot(ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,""));if(slot===null){return;}this._slot=slot;var displayTimeline=null;if(dragonBones.DataParser.DISPLAY_FRAME in rawData){displayTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.DISPLAY_FRAME,20,false,false,0,this._parseSlotDisplayFrame);}else {displayTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,20,false,false,0,this._parseSlotDisplayFrame);}if(displayTimeline!==null){this._animation.addSlotTimeline(slot,displayTimeline);}var colorTimeline=null;if(dragonBones.DataParser.COLOR_FRAME in rawData){colorTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.COLOR_FRAME,21,true,false,1,this._parseSlotColorFrame);}else {colorTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,21,true,false,1,this._parseSlotColorFrame);}if(colorTimeline!==null){this._animation.addSlotTimeline(slot,colorTimeline);}this._slot=null;};ObjectDataParser.prototype._parseFrame=function(rawData,frameStart,frameCount){var frameOffset=this._frameArray.length;this._frameArray.length+=1;this._frameArray[frameOffset+0]=frameStart;return frameOffset;};ObjectDataParser.prototype._parseTweenFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);if(frameCount>0){if(dragonBones.DataParser.CURVE in rawData){var sampleCount=frameCount+1;this._helpArray.length=sampleCount;this._samplingEasingCurve(rawData[dragonBones.DataParser.CURVE],this._helpArray);this._frameArray.length+=1+1+this._helpArray.length;this._frameArray[frameOffset+1]=2;this._frameArray[frameOffset+2]=sampleCount;for(var i=0;i<sampleCount;++i){this._frameArray[frameOffset+3+i]=Math.round(this._helpArray[i]*10000.0);}}else {var noTween=-2.0;var tweenEasing=noTween;if(dragonBones.DataParser.TWEEN_EASING in rawData){tweenEasing=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TWEEN_EASING,noTween);}if(tweenEasing===noTween){this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;}else if(tweenEasing===0.0){this._frameArray.length+=1;this._frameArray[frameOffset+1]=1;}else if(tweenEasing<0.0){this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=3;this._frameArray[frameOffset+2]=Math.round(-tweenEasing*100.0);}else if(tweenEasing<=1.0){this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=4;this._frameArray[frameOffset+2]=Math.round(tweenEasing*100.0);}else {this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=5;this._frameArray[frameOffset+2]=Math.round(tweenEasing*100.0-100.0);}}}else {this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;}return frameOffset;};ObjectDataParser.prototype._parseActionFrame=function(frame,frameStart,frameCount){var frameOffset=this._frameArray.length;var actionCount=frame.actions.length;this._frameArray.length+=1+1+actionCount;this._frameArray[frameOffset+0]=frameStart;this._frameArray[frameOffset+0+1]=actionCount;for(var i=0;i<actionCount;++i){this._frameArray[frameOffset+0+2+i]=frame.actions[i];}return frameOffset;};ObjectDataParser.prototype._parseZOrderFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);if(dragonBones.DataParser.Z_ORDER in rawData){var rawZOrder=rawData[dragonBones.DataParser.Z_ORDER];if(rawZOrder.length>0){var slotCount=this._armature.sortedSlots.length;var unchanged=new Array(slotCount-rawZOrder.length/2);var zOrders=new Array(slotCount);for(var i_1=0;i_1<unchanged.length;++i_1){unchanged[i_1]=0;}for(var i_2=0;i_2<slotCount;++i_2){zOrders[i_2]=-1;}var originalIndex=0;var unchangedIndex=0;for(var i_3=0,l=rawZOrder.length;i_3<l;i_3+=2){var slotIndex=rawZOrder[i_3];var zOrderOffset=rawZOrder[i_3+1];while(originalIndex!==slotIndex){unchanged[unchangedIndex++]=originalIndex++;}var index=originalIndex+zOrderOffset;zOrders[index]=originalIndex++;}while(originalIndex<slotCount){unchanged[unchangedIndex++]=originalIndex++;}this._frameArray.length+=1+slotCount;this._frameArray[frameOffset+1]=slotCount;var i=slotCount;while(i--){if(zOrders[i]===-1){this._frameArray[frameOffset+2+i]=unchanged[--unchangedIndex]||0;}else {this._frameArray[frameOffset+2+i]=zOrders[i]||0;}}return frameOffset;}}this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;return frameOffset;};ObjectDataParser.prototype._parseBoneAllFrame=function(rawData,frameStart,frameCount){this._helpTransform.identity();if(dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],this._helpTransform,1.0);}var rotation=this._helpTransform.rotation;if(frameStart!==0){if(this._prevClockwise===0){rotation=this._prevRotation+dragonBones.Transform.normalizeRadian(rotation-this._prevRotation);}else {if(this._prevClockwise>0?rotation>=this._prevRotation:rotation<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1;}rotation=this._prevRotation+rotation-this._prevRotation+dragonBones.Transform.PI_D*this._prevClockwise;}}this._prevClockwise=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TWEEN_ROTATE,0.0);this._prevRotation=rotation;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=6;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.x;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.y;this._frameFloatArray[frameFloatOffset++]=rotation;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.skew;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.scaleX;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.scaleY;this._parseActionDataInFrame(rawData,frameStart,this._bone,this._slot);return frameOffset;};ObjectDataParser.prototype._parseBoneTranslateFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,0.0);this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,0.0);return frameOffset;};ObjectDataParser.prototype._parseBoneRotateFrame=function(rawData,frameStart,frameCount){var rotation=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE,0.0)*dragonBones.Transform.DEG_RAD;if(frameStart!==0){if(this._prevClockwise===0){rotation=this._prevRotation+dragonBones.Transform.normalizeRadian(rotation-this._prevRotation);}else {if(this._prevClockwise>0?rotation>=this._prevRotation:rotation<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1;}rotation=this._prevRotation+rotation-this._prevRotation+dragonBones.Transform.PI_D*this._prevClockwise;}}this._prevClockwise=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.CLOCK_WISE,0);this._prevRotation=rotation;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=rotation;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW,0.0)*dragonBones.Transform.DEG_RAD;return frameOffset;};ObjectDataParser.prototype._parseBoneScaleFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,1.0);this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,1.0);return frameOffset;};ObjectDataParser.prototype._parseSurfaceFrame=function(rawData,frameStart,frameCount){var frameFloatOffset=this._frameFloatArray.length;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var rawVertices=rawData[dragonBones.DataParser.VERTICES];var offset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0);var vertexCount=this._surface.vertices.length/2;var x=0.0;var y=0.0;this._frameFloatArray.length+=vertexCount*2;for(var i=0;i<vertexCount*2;i+=2){if(i<offset||i-offset>=rawVertices.length){x=0.0;}else {x=rawVertices[i-offset];}if(i+1<offset||i+1-offset>=rawVertices.length){y=0.0;}else {y=rawVertices[i+1-offset];}this._frameFloatArray[frameFloatOffset+i]=x;this._frameFloatArray[frameFloatOffset+i+1]=y;}if(frameStart===0){var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1+1+1+1+1;this._frameIntArray[frameIntOffset+0]=0;this._frameIntArray[frameIntOffset+1]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+2]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+3]=0;this._frameIntArray[frameIntOffset+4]=frameFloatOffset-this._animation.frameFloatOffset;this._timelineArray[this._timeline.offset+3]=frameIntOffset-this._animation.frameIntOffset;}return frameOffset;};ObjectDataParser.prototype._parseSlotDisplayFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);this._frameArray.length+=1;if(dragonBones.DataParser.VALUE in rawData){this._frameArray[frameOffset+1]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VALUE,0);}else {this._frameArray[frameOffset+1]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DISPLAY_INDEX,0);}this._parseActionDataInFrame(rawData,frameStart,this._slot.parent,this._slot);return frameOffset;};ObjectDataParser.prototype._parseSlotColorFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var colorOffset=-1;if(dragonBones.DataParser.VALUE in rawData||dragonBones.DataParser.COLOR in rawData){var rawColor=dragonBones.DataParser.VALUE in rawData?rawData[dragonBones.DataParser.VALUE]:rawData[dragonBones.DataParser.COLOR];for(var k in rawColor){this._parseColorTransform(rawColor,this._helpColorTransform);colorOffset=this._intArray.length;this._intArray.length+=8;this._intArray[colorOffset++]=Math.round(this._helpColorTransform.alphaMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.redMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.greenMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.blueMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.alphaOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.redOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.greenOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.blueOffset);colorOffset-=8;break;}}if(colorOffset<0){if(this._defaultColorOffset<0){this._defaultColorOffset=colorOffset=this._intArray.length;this._intArray.length+=8;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;}colorOffset=this._defaultColorOffset;}var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1;this._frameIntArray[frameIntOffset]=colorOffset;return frameOffset;};ObjectDataParser.prototype._parseSlotFFDFrame=function(rawData,frameStart,frameCount){var frameFloatOffset=this._frameFloatArray.length;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var rawVertices=dragonBones.DataParser.VERTICES in rawData?rawData[dragonBones.DataParser.VERTICES]:null;var offset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0);var vertexCount=this._intArray[this._mesh.vertices.offset+0];var meshName=this._mesh.parent.name+"_"+this._slot.name+"_"+this._mesh.name;var weight=this._mesh.vertices.weight;var x=0.0;var y=0.0;var iB=0;var iV=0;if(weight!==null){var rawSlotPose=this._weightSlotPose[meshName];this._helpMatrixA.copyFromArray(rawSlotPose,0);this._frameFloatArray.length+=weight.count*2;iB=weight.offset+2+weight.bones.length;}else {this._frameFloatArray.length+=vertexCount*2;}for(var i=0;i<vertexCount*2;i+=2){if(rawVertices===null){x=0.0;y=0.0;}else {if(i<offset||i-offset>=rawVertices.length){x=0.0;}else {x=rawVertices[i-offset];}if(i+1<offset||i+1-offset>=rawVertices.length){y=0.0;}else {y=rawVertices[i+1-offset];}}if(weight!==null){var rawBonePoses=this._weightBonePoses[meshName];var vertexBoneCount=this._intArray[iB++];this._helpMatrixA.transformPoint(x,y,this._helpPoint,true);x=this._helpPoint.x;y=this._helpPoint.y;for(var j=0;j<vertexBoneCount;++j){var boneIndex=this._intArray[iB++];this._helpMatrixB.copyFromArray(rawBonePoses,boneIndex*7+1);this._helpMatrixB.invert();this._helpMatrixB.transformPoint(x,y,this._helpPoint,true);this._frameFloatArray[frameFloatOffset+iV++]=this._helpPoint.x;this._frameFloatArray[frameFloatOffset+iV++]=this._helpPoint.y;}}else {this._frameFloatArray[frameFloatOffset+i]=x;this._frameFloatArray[frameFloatOffset+i+1]=y;}}if(frameStart===0){var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1+1+1+1+1;this._frameIntArray[frameIntOffset+0]=this._mesh.vertices.offset;this._frameIntArray[frameIntOffset+1]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+2]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+3]=0;this._frameIntArray[frameIntOffset+4]=frameFloatOffset-this._animation.frameFloatOffset;this._timelineArray[this._timeline.offset+3]=frameIntOffset-this._animation.frameIntOffset;}return frameOffset;};ObjectDataParser.prototype._parseIKConstraintFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=2;this._frameIntArray[frameIntOffset++]=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.BEND_POSITIVE,true)?1:0;this._frameIntArray[frameIntOffset++]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0)*100.0);return frameOffset;};ObjectDataParser.prototype._parseAnimationFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=2;this._frameIntArray[frameIntOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VALUE,0);this._frameIntArray[frameIntOffset++]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0)*100.0);return frameOffset;};ObjectDataParser.prototype._parseActionData=function(rawData,type,bone,slot){var actions=new Array();if(typeof rawData==="string"){var action=dragonBones.BaseObject.borrowObject(dragonBones.ActionData);action.type=type;action.name=rawData;action.bone=bone;action.slot=slot;actions.push(action);}else if(rawData instanceof Array){for(var _i=0,rawData_2=rawData;_i<rawData_2.length;_i++){var rawAction=rawData_2[_i];var action=dragonBones.BaseObject.borrowObject(dragonBones.ActionData);if(dragonBones.DataParser.GOTO_AND_PLAY in rawAction){action.type=0;action.name=ObjectDataParser._getString(rawAction,dragonBones.DataParser.GOTO_AND_PLAY,"");}else {if(dragonBones.DataParser.TYPE in rawAction&&typeof rawAction[dragonBones.DataParser.TYPE]==="string"){action.type=dragonBones.DataParser._getActionType(rawAction[dragonBones.DataParser.TYPE]);}else {action.type=ObjectDataParser._getNumber(rawAction,dragonBones.DataParser.TYPE,type);}action.name=ObjectDataParser._getString(rawAction,dragonBones.DataParser.NAME,"");}if(dragonBones.DataParser.BONE in rawAction){var boneName=ObjectDataParser._getString(rawAction,dragonBones.DataParser.BONE,"");action.bone=this._armature.getBone(boneName);}else {action.bone=bone;}if(dragonBones.DataParser.SLOT in rawAction){var slotName=ObjectDataParser._getString(rawAction,dragonBones.DataParser.SLOT,"");action.slot=this._armature.getSlot(slotName);}else {action.slot=slot;}var userData=null;if(dragonBones.DataParser.INTS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawInts=rawAction[dragonBones.DataParser.INTS];for(var _a=0,rawInts_1=rawInts;_a<rawInts_1.length;_a++){var rawValue=rawInts_1[_a];userData.addInt(rawValue);}}if(dragonBones.DataParser.FLOATS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawFloats=rawAction[dragonBones.DataParser.FLOATS];for(var _b=0,rawFloats_1=rawFloats;_b<rawFloats_1.length;_b++){var rawValue=rawFloats_1[_b];userData.addFloat(rawValue);}}if(dragonBones.DataParser.STRINGS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawStrings=rawAction[dragonBones.DataParser.STRINGS];for(var _c=0,rawStrings_1=rawStrings;_c<rawStrings_1.length;_c++){var rawValue=rawStrings_1[_c];userData.addString(rawValue);}}action.data=userData;actions.push(action);}}return actions;};ObjectDataParser.prototype._parseTransform=function(rawData,transform,scale){transform.x=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,0.0)*scale;transform.y=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,0.0)*scale;if(dragonBones.DataParser.ROTATE in rawData||dragonBones.DataParser.SKEW in rawData){transform.rotation=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE,0.0)*dragonBones.Transform.DEG_RAD);transform.skew=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW,0.0)*dragonBones.Transform.DEG_RAD);}else if(dragonBones.DataParser.SKEW_X in rawData||dragonBones.DataParser.SKEW_Y in rawData){transform.rotation=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW_Y,0.0)*dragonBones.Transform.DEG_RAD);transform.skew=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW_X,0.0)*dragonBones.Transform.DEG_RAD)-transform.rotation;}transform.scaleX=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE_X,1.0);transform.scaleY=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE_Y,1.0);};ObjectDataParser.prototype._parseColorTransform=function(rawData,color){color.alphaMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ALPHA_MULTIPLIER,100)*0.01;color.redMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.RED_MULTIPLIER,100)*0.01;color.greenMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.GREEN_MULTIPLIER,100)*0.01;color.blueMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLUE_MULTIPLIER,100)*0.01;color.alphaOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ALPHA_OFFSET,0);color.redOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.RED_OFFSET,0);color.greenOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.GREEN_OFFSET,0);color.blueOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLUE_OFFSET,0);};ObjectDataParser.prototype._parseArray=function(rawData){this._intArray.length=0;this._floatArray.length=0;this._frameIntArray.length=0;this._frameFloatArray.length=0;this._frameArray.length=0;this._timelineArray.length=0;};ObjectDataParser.prototype._modifyArray=function(){if(this._intArray.length%2!==0){this._intArray.push(0);}if(this._frameIntArray.length%2!==0){this._frameIntArray.push(0);}if(this._frameArray.length%2!==0){this._frameArray.push(0);}if(this._timelineArray.length%2!==0){this._timelineArray.push(0);}var l1=this._intArray.length*2;var l2=this._floatArray.length*4;var l3=this._frameIntArray.length*2;var l4=this._frameFloatArray.length*4;var l5=this._frameArray.length*2;var l6=this._timelineArray.length*2;var lTotal=l1+l2+l3+l4+l5+l6;if(dragonBones.DragonBones.webAssembly){var shareBuffer=dragonBones.webAssemblyModule.HEAP16.buffer;var bufferPointer=dragonBones.webAssemblyModule._malloc(lTotal);var intArray=new Int16Array(shareBuffer,bufferPointer,this._intArray.length);var floatArray=new Float32Array(shareBuffer,bufferPointer+l1,this._floatArray.length);var frameIntArray=new Int16Array(shareBuffer,bufferPointer+l1+l2,this._frameIntArray.length);var frameFloatArray=new Float32Array(shareBuffer,bufferPointer+l1+l2+l3,this._frameFloatArray.length);var frameArray=new Int16Array(shareBuffer,bufferPointer+l1+l2+l3+l4,this._frameArray.length);var timelineArray=new Uint16Array(shareBuffer,bufferPointer+l1+l2+l3+l4+l5,this._timelineArray.length);for(var i=0,l=this._intArray.length;i<l;++i){intArray[i]=this._intArray[i];}for(var i=0,l=this._floatArray.length;i<l;++i){floatArray[i]=this._floatArray[i];}for(var i=0,l=this._frameIntArray.length;i<l;++i){frameIntArray[i]=this._frameIntArray[i];}for(var i=0,l=this._frameFloatArray.length;i<l;++i){frameFloatArray[i]=this._frameFloatArray[i];}for(var i=0,l=this._frameArray.length;i<l;++i){frameArray[i]=this._frameArray[i];}for(var i=0,l=this._timelineArray.length;i<l;++i){timelineArray[i]=this._timelineArray[i];}dragonBones.webAssemblyModule.setDataBinary(this._data,bufferPointer,l1,l2,l3,l4,l5,l6);}else {var binary=new ArrayBuffer(lTotal);var intArray=new Int16Array(binary,0,this._intArray.length);var floatArray=new Float32Array(binary,l1,this._floatArray.length);var frameIntArray=new Int16Array(binary,l1+l2,this._frameIntArray.length);var frameFloatArray=new Float32Array(binary,l1+l2+l3,this._frameFloatArray.length);var frameArray=new Int16Array(binary,l1+l2+l3+l4,this._frameArray.length);var timelineArray=new Uint16Array(binary,l1+l2+l3+l4+l5,this._timelineArray.length);for(var i=0,l=this._intArray.length;i<l;++i){intArray[i]=this._intArray[i];}for(var i=0,l=this._floatArray.length;i<l;++i){floatArray[i]=this._floatArray[i];}for(var i=0,l=this._frameIntArray.length;i<l;++i){frameIntArray[i]=this._frameIntArray[i];}for(var i=0,l=this._frameFloatArray.length;i<l;++i){frameFloatArray[i]=this._frameFloatArray[i];}for(var i=0,l=this._frameArray.length;i<l;++i){frameArray[i]=this._frameArray[i];}for(var i=0,l=this._timelineArray.length;i<l;++i){timelineArray[i]=this._timelineArray[i];}this._data.binary=binary;this._data.intArray=intArray;this._data.floatArray=floatArray;this._data.frameIntArray=frameIntArray;this._data.frameFloatArray=frameFloatArray;this._data.frameArray=frameArray;this._data.timelineArray=timelineArray;}this._defaultColorOffset=-1;};ObjectDataParser.prototype.parseDragonBonesData=function(rawData,scale){if(scale===void 0){scale=1;}console.assert(rawData!==null&&rawData!==undefined,"Data error.");var version=ObjectDataParser._getString(rawData,dragonBones.DataParser.VERSION,"");var compatibleVersion=ObjectDataParser._getString(rawData,dragonBones.DataParser.COMPATIBLE_VERSION,"");if(dragonBones.DataParser.DATA_VERSIONS.indexOf(version)>=0||dragonBones.DataParser.DATA_VERSIONS.indexOf(compatibleVersion)>=0){var data=dragonBones.BaseObject.borrowObject(dragonBones.DragonBonesData);data.version=version;data.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");data.frameRate=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FRAME_RATE,24);if(data.frameRate===0){data.frameRate=24;}if(dragonBones.DataParser.ARMATURE in rawData){this._data=data;this._parseArray(rawData);var rawArmatures=rawData[dragonBones.DataParser.ARMATURE];for(var _i=0,rawArmatures_1=rawArmatures;_i<rawArmatures_1.length;_i++){var rawArmature=rawArmatures_1[_i];data.addArmature(this._parseArmature(rawArmature,scale));}if(!this._data.binary){this._modifyArray();}if(dragonBones.DataParser.STAGE in rawData){data.stage=data.getArmature(ObjectDataParser._getString(rawData,dragonBones.DataParser.STAGE,""));}else if(data.armatureNames.length>0){data.stage=data.getArmature(data.armatureNames[0]);}this._data=null;}if(dragonBones.DataParser.TEXTURE_ATLAS in rawData){this._rawTextureAtlases=rawData[dragonBones.DataParser.TEXTURE_ATLAS];}return data;}else {console.assert(false,"Nonsupport data version: "+version+"\n"+"Please convert DragonBones data to support version.\n"+"Read more: https://github.com/DragonBones/Tools/");}return null;};ObjectDataParser.prototype.parseTextureAtlasData=function(rawData,textureAtlasData,scale){if(scale===void 0){scale=1.0;}console.assert(rawData!==undefined);if(rawData===null){if(this._rawTextureAtlases===null||this._rawTextureAtlases.length===0){return false;}var rawTextureAtlas=this._rawTextureAtlases[this._rawTextureAtlasIndex++];this.parseTextureAtlasData(rawTextureAtlas,textureAtlasData,scale);if(this._rawTextureAtlasIndex>=this._rawTextureAtlases.length){this._rawTextureAtlasIndex=0;this._rawTextureAtlases=null;}return true;}textureAtlasData.width=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WIDTH,0);textureAtlasData.height=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.HEIGHT,0);textureAtlasData.scale=scale===1.0?1.0/ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0):scale;textureAtlasData.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");textureAtlasData.imagePath=ObjectDataParser._getString(rawData,dragonBones.DataParser.IMAGE_PATH,"");if(dragonBones.DataParser.SUB_TEXTURE in rawData){var rawTextures=rawData[dragonBones.DataParser.SUB_TEXTURE];for(var i=0,l=rawTextures.length;i<l;++i){var rawTexture=rawTextures[i];var textureData=textureAtlasData.createTexture();textureData.rotated=ObjectDataParser._getBoolean(rawTexture,dragonBones.DataParser.ROTATED,false);textureData.name=ObjectDataParser._getString(rawTexture,dragonBones.DataParser.NAME,"");textureData.region.x=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.X,0.0);textureData.region.y=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.Y,0.0);textureData.region.width=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.WIDTH,0.0);textureData.region.height=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.HEIGHT,0.0);var frameWidth=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_WIDTH,-1.0);var frameHeight=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_HEIGHT,-1.0);if(frameWidth>0.0&&frameHeight>0.0){textureData.frame=dragonBones.TextureData.createRectangle();textureData.frame.x=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_X,0.0);textureData.frame.y=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_Y,0.0);textureData.frame.width=frameWidth;textureData.frame.height=frameHeight;}textureAtlasData.addTexture(textureData);}}return true;};ObjectDataParser.getInstance=function(){if(ObjectDataParser._objectDataParserInstance===null){ObjectDataParser._objectDataParserInstance=new ObjectDataParser();}return ObjectDataParser._objectDataParserInstance;};ObjectDataParser._objectDataParserInstance=null;return ObjectDataParser;}(dragonBones.DataParser);dragonBones.ObjectDataParser=ObjectDataParser;var ActionFrame=function(){function ActionFrame(){this.frameStart=0;this.actions=[];}return ActionFrame;}();dragonBones.ActionFrame=ActionFrame;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var BinaryDataParser=function(_super){__extends(BinaryDataParser,_super);function BinaryDataParser(){return _super!==null&&_super.apply(this,arguments)||this;}BinaryDataParser.prototype._inRange=function(a,min,max){return min<=a&&a<=max;};BinaryDataParser.prototype._decodeUTF8=function(data){var EOF_byte=-1;var EOF_code_point=-1;var FATAL_POINT=0xFFFD;var pos=0;var result="";var code_point;var utf8_code_point=0;var utf8_bytes_needed=0;var utf8_bytes_seen=0;var utf8_lower_boundary=0;while(data.length>pos){var _byte=data[pos++];if(_byte===EOF_byte){if(utf8_bytes_needed!==0){code_point=FATAL_POINT;}else {code_point=EOF_code_point;}}else {if(utf8_bytes_needed===0){if(this._inRange(_byte,0x00,0x7F)){code_point=_byte;}else {if(this._inRange(_byte,0xC2,0xDF)){utf8_bytes_needed=1;utf8_lower_boundary=0x80;utf8_code_point=_byte-0xC0;}else if(this._inRange(_byte,0xE0,0xEF)){utf8_bytes_needed=2;utf8_lower_boundary=0x800;utf8_code_point=_byte-0xE0;}else if(this._inRange(_byte,0xF0,0xF4)){utf8_bytes_needed=3;utf8_lower_boundary=0x10000;utf8_code_point=_byte-0xF0;}else;utf8_code_point=utf8_code_point*Math.pow(64,utf8_bytes_needed);code_point=null;}}else if(!this._inRange(_byte,0x80,0xBF)){utf8_code_point=0;utf8_bytes_needed=0;utf8_bytes_seen=0;utf8_lower_boundary=0;pos--;code_point=_byte;}else {utf8_bytes_seen+=1;utf8_code_point=utf8_code_point+(_byte-0x80)*Math.pow(64,utf8_bytes_needed-utf8_bytes_seen);if(utf8_bytes_seen!==utf8_bytes_needed){code_point=null;}else {var cp=utf8_code_point;var lower_boundary=utf8_lower_boundary;utf8_code_point=0;utf8_bytes_needed=0;utf8_bytes_seen=0;utf8_lower_boundary=0;if(this._inRange(cp,lower_boundary,0x10FFFF)&&!this._inRange(cp,0xD800,0xDFFF)){code_point=cp;}else {code_point=_byte;}}}}if(code_point!==null&&code_point!==EOF_code_point){if(code_point<=0xFFFF){if(code_point>0)result+=String.fromCharCode(code_point);}else {code_point-=0x10000;result+=String.fromCharCode(0xD800+(code_point>>10&0x3ff));result+=String.fromCharCode(0xDC00+(code_point&0x3ff));}}}return result;};BinaryDataParser.prototype._getUTF16Key=function(value){for(var i=0,l=value.length;i<l;++i){if(value.charCodeAt(i)>255){return encodeURI(value);}}return value;};BinaryDataParser.prototype._parseBinaryTimeline=function(type,offset,timelineData){if(timelineData===void 0){timelineData=null;}var timeline=timelineData!==null?timelineData:dragonBones.BaseObject.borrowObject(dragonBones.TimelineData);timeline.type=type;timeline.offset=offset;this._timeline=timeline;var keyFrameCount=this._timelineArrayBuffer[timeline.offset+2];if(keyFrameCount===1){timeline.frameIndicesOffset=-1;}else {var frameIndicesOffset=0;var totalFrameCount=this._animation.frameCount+1;var frameIndices=this._data.frameIndices;if(dragonBones.DragonBones.webAssembly){frameIndicesOffset=frameIndices.size();frameIndices.resize(frameIndicesOffset+totalFrameCount,0);}else {frameIndicesOffset=frameIndices.length;frameIndices.length+=totalFrameCount;}timeline.frameIndicesOffset=frameIndicesOffset;for(var i=0,iK=0,frameStart=0,frameCount=0;i<totalFrameCount;++i){if(frameStart+frameCount<=i&&iK<keyFrameCount){frameStart=this._frameArrayBuffer[this._animation.frameOffset+this._timelineArrayBuffer[timeline.offset+5+iK]];if(iK===keyFrameCount-1){frameCount=this._animation.frameCount-frameStart;}else {frameCount=this._frameArrayBuffer[this._animation.frameOffset+this._timelineArrayBuffer[timeline.offset+5+iK+1]]-frameStart;}iK++;}if(dragonBones.DragonBones.webAssembly){frameIndices.set(frameIndicesOffset+i,iK-1);}else {frameIndices[frameIndicesOffset+i]=iK-1;}}}this._timeline=null;return timeline;};BinaryDataParser.prototype._parseVertices=function(rawData,vertices){vertices.offset=rawData[dragonBones.DataParser.OFFSET];var weightOffset=this._intArrayBuffer[vertices.offset+3];if(weightOffset>=0){var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);var vertexCount=this._intArrayBuffer[vertices.offset+0];var boneCount=this._intArrayBuffer[weightOffset+0];weight.offset=weightOffset;for(var i=0;i<boneCount;++i){var boneIndex=this._intArrayBuffer[weightOffset+2+i];weight.addBone(this._rawBones[boneIndex]);}var boneIndicesOffset=weightOffset+2+boneCount;var weightCount=0;for(var i=0,l=vertexCount;i<l;++i){var vertexBoneCount=this._intArrayBuffer[boneIndicesOffset++];weightCount+=vertexBoneCount;boneIndicesOffset+=vertexBoneCount;}weight.count=weightCount;vertices.weight=weight;}};BinaryDataParser.prototype._parseMesh=function(rawData,mesh){this._parseVertices(rawData,mesh.vertices);};BinaryDataParser.prototype._parsePath=function(rawData,path){this._parseVertices(rawData,path.vertices);};BinaryDataParser.prototype._parseAnimation=function(rawData){var animation=dragonBones.BaseObject.borrowObject(dragonBones.AnimationData);animation.frameCount=Math.max(dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DURATION,1),1);animation.playTimes=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.PLAY_TIMES,1);animation.duration=animation.frameCount/this._armature.frameRate;animation.fadeInTime=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FADE_IN_TIME,0.0);animation.scale=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0);animation.name=dragonBones.ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(animation.name.length===0){animation.name=dragonBones.DataParser.DEFAULT_NAME;}var offsets=rawData[dragonBones.DataParser.OFFSET];animation.frameIntOffset=offsets[0];animation.frameFloatOffset=offsets[1];animation.frameOffset=offsets[2];this._animation=animation;if(dragonBones.DataParser.ACTION in rawData){animation.actionTimeline=this._parseBinaryTimeline(0,rawData[dragonBones.DataParser.ACTION]);}if(dragonBones.DataParser.Z_ORDER in rawData){animation.zOrderTimeline=this._parseBinaryTimeline(1,rawData[dragonBones.DataParser.Z_ORDER]);}if(dragonBones.DataParser.BONE in rawData){var rawTimeliness=rawData[dragonBones.DataParser.BONE];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var bone=this._armature.getBone(k);if(bone===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addBoneTimeline(bone,timeline);}}}if(dragonBones.DataParser.SURFACE in rawData){var rawTimeliness=rawData[dragonBones.DataParser.SURFACE];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var surface=this._armature.getBone(k);if(surface===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addSurfaceTimeline(surface,timeline);}}}if(dragonBones.DataParser.SLOT in rawData){var rawTimeliness=rawData[dragonBones.DataParser.SLOT];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var slot=this._armature.getSlot(k);if(slot===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addSlotTimeline(slot,timeline);}}}if(dragonBones.DataParser.CONSTRAINT in rawData){var rawTimeliness=rawData[dragonBones.DataParser.CONSTRAINT];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var constraint=this._armature.getConstraint(k);if(constraint===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addConstraintTimeline(constraint,timeline);}}}if(dragonBones.DataParser.ANIMATION in rawData){var rawTimeliness=rawData[dragonBones.DataParser.ANIMATION];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addAnimationTimeline(k,timeline);}}}this._animation=null;return animation;};BinaryDataParser.prototype._parseArray=function(rawData){var offsets=rawData[dragonBones.DataParser.OFFSET];var l1=offsets[1];var l2=offsets[3];var l3=offsets[5];var l4=offsets[7];var l5=offsets[9];var l6=offsets[11];var intArray=new Int16Array(this._binary,this._binaryOffset+offsets[0],l1/2);var floatArray=new Float32Array(this._binary,this._binaryOffset+offsets[2],l2/4);var frameIntArray=new Int16Array(this._binary,this._binaryOffset+offsets[4],l3/2);var frameFloatArray=new Float32Array(this._binary,this._binaryOffset+offsets[6],l4/4);var frameArray=new Int16Array(this._binary,this._binaryOffset+offsets[8],l5/2);var timelineArray=new Uint16Array(this._binary,this._binaryOffset+offsets[10],l6/2);if(dragonBones.DragonBones.webAssembly){var lTotal=l1+l2+l3+l4+l5+l6;var bufferPointer=dragonBones.webAssemblyModule._malloc(lTotal);var rawArray=new Uint8Array(this._binary,this._binaryOffset,lTotal/1);var copyArray=new Uint8Array(dragonBones.webAssemblyModule.HEAP16.buffer,bufferPointer,rawArray.length);for(var i=0,l=rawArray.length;i<l;++i){copyArray[i]=rawArray[i];}dragonBones.webAssemblyModule.setDataBinary(this._data,bufferPointer,l1,l2,l3,l4,l5,l6);this._intArrayBuffer=intArray;this._floatArrayBuffer=floatArray;this._frameIntArrayBuffer=frameIntArray;this._frameFloatArrayBuffer=frameFloatArray;this._frameArrayBuffer=frameArray;this._timelineArrayBuffer=timelineArray;}else {this._data.binary=this._binary;this._data.intArray=this._intArrayBuffer=intArray;this._data.floatArray=this._floatArrayBuffer=floatArray;this._data.frameIntArray=this._frameIntArrayBuffer=frameIntArray;this._data.frameFloatArray=this._frameFloatArrayBuffer=frameFloatArray;this._data.frameArray=this._frameArrayBuffer=frameArray;this._data.timelineArray=this._timelineArrayBuffer=timelineArray;}};BinaryDataParser.prototype.parseDragonBonesData=function(rawData,scale){if(scale===void 0){scale=1;}console.assert(rawData!==null&&rawData!==undefined&&rawData instanceof ArrayBuffer,"Data error.");var tag=new Uint8Array(rawData,0,8);if(tag[0]!=="D".charCodeAt(0)||tag[1]!=="B".charCodeAt(0)||tag[2]!=="D".charCodeAt(0)||tag[3]!=="T".charCodeAt(0)){console.assert(false,"Nonsupport data.");return null;}var headerLength=new Uint32Array(rawData,8,1)[0];var headerBytes=new Uint8Array(rawData,8+4,headerLength);var headerString=this._decodeUTF8(headerBytes);var header=JSON.parse(headerString);this._binaryOffset=8+4+headerLength;this._binary=rawData;return _super.prototype.parseDragonBonesData.call(this,header,scale);};BinaryDataParser.getInstance=function(){if(BinaryDataParser._binaryDataParserInstance===null){BinaryDataParser._binaryDataParserInstance=new BinaryDataParser();}return BinaryDataParser._binaryDataParserInstance;};BinaryDataParser._binaryDataParserInstance=null;return BinaryDataParser;}(dragonBones.ObjectDataParser);dragonBones.BinaryDataParser=BinaryDataParser;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){var BaseFactory=function(){function BaseFactory(dataParser){if(dataParser===void 0){dataParser=null;}this.autoSearch=false;this._dragonBonesDataMap={};this._textureAtlasDataMap={};this._dragonBones=null;this._dataParser=null;if(BaseFactory._objectParser===null){BaseFactory._objectParser=new dragonBones.ObjectDataParser();}if(BaseFactory._binaryParser===null){BaseFactory._binaryParser=new dragonBones.BinaryDataParser();}this._dataParser=dataParser!==null?dataParser:BaseFactory._objectParser;}BaseFactory.prototype._isSupportMesh=function(){return true;};BaseFactory.prototype._getTextureData=function(textureAtlasName,textureName){if(textureAtlasName in this._textureAtlasDataMap){for(var _i=0,_a=this._textureAtlasDataMap[textureAtlasName];_i<_a.length;_i++){var textureAtlasData=_a[_i];var textureData=textureAtlasData.getTexture(textureName);if(textureData!==null){return textureData;}}}if(this.autoSearch){for(var k in this._textureAtlasDataMap){for(var _b=0,_c=this._textureAtlasDataMap[k];_b<_c.length;_b++){var textureAtlasData=_c[_b];if(textureAtlasData.autoSearch){var textureData=textureAtlasData.getTexture(textureName);if(textureData!==null){return textureData;}}}}}return null;};BaseFactory.prototype._fillBuildArmaturePackage=function(dataPackage,dragonBonesName,armatureName,skinName,textureAtlasName){var dragonBonesData=null;var armatureData=null;if(dragonBonesName.length>0){if(dragonBonesName in this._dragonBonesDataMap){dragonBonesData=this._dragonBonesDataMap[dragonBonesName];armatureData=dragonBonesData.getArmature(armatureName);}}if(armatureData===null&&(dragonBonesName.length===0||this.autoSearch)){for(var k in this._dragonBonesDataMap){dragonBonesData=this._dragonBonesDataMap[k];if(dragonBonesName.length===0||dragonBonesData.autoSearch){armatureData=dragonBonesData.getArmature(armatureName);if(armatureData!==null){dragonBonesName=k;break;}}}}if(armatureData!==null){dataPackage.dataName=dragonBonesName;dataPackage.textureAtlasName=textureAtlasName;dataPackage.data=dragonBonesData;dataPackage.armature=armatureData;dataPackage.skin=null;if(skinName.length>0){dataPackage.skin=armatureData.getSkin(skinName);if(dataPackage.skin===null&&this.autoSearch){for(var k in this._dragonBonesDataMap){var skinDragonBonesData=this._dragonBonesDataMap[k];var skinArmatureData=skinDragonBonesData.getArmature(skinName);if(skinArmatureData!==null){dataPackage.skin=skinArmatureData.defaultSkin;break;}}}}if(dataPackage.skin===null){dataPackage.skin=armatureData.defaultSkin;}return true;}return false;};BaseFactory.prototype._buildBones=function(dataPackage,armature){for(var _i=0,_a=dataPackage.armature.sortedBones;_i<_a.length;_i++){var boneData=_a[_i];var bone=dragonBones.BaseObject.borrowObject(boneData.type===0?dragonBones.Bone:dragonBones.Surface);bone.init(boneData,armature);}};BaseFactory.prototype._buildSlots=function(dataPackage,armature){var currentSkin=dataPackage.skin;var defaultSkin=dataPackage.armature.defaultSkin;if(currentSkin===null||defaultSkin===null){return;}var skinSlots={};for(var k in defaultSkin.displays){var displays=defaultSkin.getDisplays(k);skinSlots[k]=displays;}if(currentSkin!==defaultSkin){for(var k in currentSkin.displays){var displays=currentSkin.getDisplays(k);skinSlots[k]=displays;}}for(var _i=0,_a=dataPackage.armature.sortedSlots;_i<_a.length;_i++){var slotData=_a[_i];var displayDatas=slotData.name in skinSlots?skinSlots[slotData.name]:null;var slot=this._buildSlot(dataPackage,slotData,armature);slot.rawDisplayDatas=displayDatas;if(displayDatas!==null){var displayList=new Array();for(var i=0,l=dragonBones.DragonBones.webAssembly?displayDatas.size():displayDatas.length;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displayDatas.get(i):displayDatas[i];if(displayData!==null){displayList.push(this._getSlotDisplay(dataPackage,displayData,null,slot));}else {displayList.push(null);}}slot._setDisplayList(displayList);}slot._setDisplayIndex(slotData.displayIndex,true);}};BaseFactory.prototype._buildConstraints=function(dataPackage,armature){var constraints=dataPackage.armature.constraints;for(var k in constraints){var constraintData=constraints[k];switch(constraintData.type){case 0:var ikConstraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraint);ikConstraint.init(constraintData,armature);armature._addConstraint(ikConstraint);break;case 1:var pathConstraint=dragonBones.BaseObject.borrowObject(dragonBones.PathConstraint);pathConstraint.init(constraintData,armature);armature._addConstraint(pathConstraint);break;default:var constraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraint);constraint.init(constraintData,armature);armature._addConstraint(constraint);break;}}};BaseFactory.prototype._buildChildArmature=function(dataPackage,slot,displayData){return this.buildArmature(displayData.path,dataPackage!==null?dataPackage.dataName:"","",dataPackage!==null?dataPackage.textureAtlasName:"");};BaseFactory.prototype._getSlotDisplay=function(dataPackage,displayData,rawDisplayData,slot){var dataName=dataPackage!==null?dataPackage.dataName:displayData.parent.parent.parent.name;var display=null;switch(displayData.type){case 0:{var imageDisplayData=displayData;if(dataPackage!==null&&dataPackage.textureAtlasName.length>0){imageDisplayData.texture=this._getTextureData(dataPackage.textureAtlasName,displayData.path);}if(imageDisplayData.texture===null){imageDisplayData.texture=this._getTextureData(dataName,displayData.path);}if(rawDisplayData!==null&&rawDisplayData.type===2&&this._isSupportMesh()){display=slot.meshDisplay;}else {display=slot.rawDisplay;}break;}case 2:{var meshDisplayData=displayData;if(dataPackage!==null&&dataPackage.textureAtlasName.length>0){meshDisplayData.texture=this._getTextureData(dataPackage.textureAtlasName,meshDisplayData.path);}if(meshDisplayData.texture===null){meshDisplayData.texture=this._getTextureData(dataName,meshDisplayData.path);}if(this._isSupportMesh()){display=slot.meshDisplay;}else {display=slot.rawDisplay;}break;}case 1:{var armatureDisplayData=displayData;var childArmature=this._buildChildArmature(dataPackage,slot,displayData);if(childArmature!==null){childArmature.inheritAnimation=armatureDisplayData.inheritAnimation;if(!childArmature.inheritAnimation){var actions=armatureDisplayData.actions.length>0?armatureDisplayData.actions:childArmature.armatureData.defaultActions;if(actions.length>0){for(var _i=0,actions_6=actions;_i<actions_6.length;_i++){var action=actions_6[_i];var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);dragonBones.EventObject.actionDataToInstance(action,eventObject,slot.armature);eventObject.slot=slot;slot.armature._bufferAction(eventObject,false);}}else {childArmature.animation.play();}}armatureDisplayData.armature=childArmature.armatureData;}display=childArmature;break;}}return display;};BaseFactory.prototype.parseDragonBonesData=function(rawData,name,scale){if(name===void 0){name=null;}if(scale===void 0){scale=1.0;}var dataParser=rawData instanceof ArrayBuffer?BaseFactory._binaryParser:this._dataParser;var dragonBonesData=dataParser.parseDragonBonesData(rawData,scale);while(true){var textureAtlasData=this._buildTextureAtlasData(null,null);if(dataParser.parseTextureAtlasData(null,textureAtlasData,scale)){this.addTextureAtlasData(textureAtlasData,name);}else {textureAtlasData.returnToPool();break;}}if(dragonBonesData!==null){this.addDragonBonesData(dragonBonesData,name);}return dragonBonesData;};BaseFactory.prototype.parseTextureAtlasData=function(rawData,textureAtlas,name,scale){if(name===void 0){name=null;}if(scale===void 0){scale=1.0;}var textureAtlasData=this._buildTextureAtlasData(null,null);this._dataParser.parseTextureAtlasData(rawData,textureAtlasData,scale);this._buildTextureAtlasData(textureAtlasData,textureAtlas||null);this.addTextureAtlasData(textureAtlasData,name);return textureAtlasData;};BaseFactory.prototype.updateTextureAtlasData=function(name,textureAtlases){var textureAtlasDatas=this.getTextureAtlasData(name);if(textureAtlasDatas!==null){for(var i=0,l=textureAtlasDatas.length;i<l;++i){if(i<textureAtlases.length){this._buildTextureAtlasData(textureAtlasDatas[i],textureAtlases[i]);}}}};BaseFactory.prototype.getDragonBonesData=function(name){return name in this._dragonBonesDataMap?this._dragonBonesDataMap[name]:null;};BaseFactory.prototype.addDragonBonesData=function(data,name){if(name===void 0){name=null;}name=name!==null?name:data.name;if(name in this._dragonBonesDataMap){if(this._dragonBonesDataMap[name]===data){return;}console.warn("Can not add same name data: "+name);return;}this._dragonBonesDataMap[name]=data;};BaseFactory.prototype.removeDragonBonesData=function(name,disposeData){if(disposeData===void 0){disposeData=true;}if(name in this._dragonBonesDataMap){if(disposeData){this._dragonBones.bufferObject(this._dragonBonesDataMap[name]);}delete this._dragonBonesDataMap[name];}};BaseFactory.prototype.getTextureAtlasData=function(name){return name in this._textureAtlasDataMap?this._textureAtlasDataMap[name]:null;};BaseFactory.prototype.addTextureAtlasData=function(data,name){if(name===void 0){name=null;}name=name!==null?name:data.name;var textureAtlasList=name in this._textureAtlasDataMap?this._textureAtlasDataMap[name]:this._textureAtlasDataMap[name]=[];if(textureAtlasList.indexOf(data)<0){textureAtlasList.push(data);}};BaseFactory.prototype.removeTextureAtlasData=function(name,disposeData){if(disposeData===void 0){disposeData=true;}if(name in this._textureAtlasDataMap){var textureAtlasDataList=this._textureAtlasDataMap[name];if(disposeData){for(var _i=0,textureAtlasDataList_1=textureAtlasDataList;_i<textureAtlasDataList_1.length;_i++){var textureAtlasData=textureAtlasDataList_1[_i];this._dragonBones.bufferObject(textureAtlasData);}}delete this._textureAtlasDataMap[name];}};BaseFactory.prototype.getArmatureData=function(name,dragonBonesName){if(dragonBonesName===void 0){dragonBonesName="";}var dataPackage=new BuildArmaturePackage();if(!this._fillBuildArmaturePackage(dataPackage,dragonBonesName,name,"","")){return null;}return dataPackage.armature;};BaseFactory.prototype.clear=function(disposeData){if(disposeData===void 0){disposeData=true;}for(var k in this._dragonBonesDataMap){if(disposeData){this._dragonBones.bufferObject(this._dragonBonesDataMap[k]);}delete this._dragonBonesDataMap[k];}for(var k in this._textureAtlasDataMap){if(disposeData){var textureAtlasDataList=this._textureAtlasDataMap[k];for(var _i=0,textureAtlasDataList_2=textureAtlasDataList;_i<textureAtlasDataList_2.length;_i++){var textureAtlasData=textureAtlasDataList_2[_i];this._dragonBones.bufferObject(textureAtlasData);}}delete this._textureAtlasDataMap[k];}};BaseFactory.prototype.buildArmature=function(armatureName,dragonBonesName,skinName,textureAtlasName){if(dragonBonesName===void 0){dragonBonesName="";}if(skinName===void 0){skinName="";}if(textureAtlasName===void 0){textureAtlasName="";}var dataPackage=new BuildArmaturePackage();if(!this._fillBuildArmaturePackage(dataPackage,dragonBonesName||"",armatureName,skinName||"",textureAtlasName||"")){console.warn("No armature data: "+armatureName+", "+(dragonBonesName!==null?dragonBonesName:""));return null;}var armature=this._buildArmature(dataPackage);this._buildBones(dataPackage,armature);this._buildSlots(dataPackage,armature);this._buildConstraints(dataPackage,armature);armature.invalidUpdate(null,true);armature.advanceTime(0.0);return armature;};BaseFactory.prototype.replaceDisplay=function(slot,displayData,displayIndex){if(displayIndex===void 0){displayIndex=-1;}if(displayIndex<0){displayIndex=slot.displayIndex;}if(displayIndex<0){displayIndex=0;}slot.replaceDisplayData(displayData,displayIndex);var displayList=slot.displayList;if(displayList.length<=displayIndex){displayList.length=displayIndex+1;for(var i=0,l=displayList.length;i<l;++i){if(!displayList[i]){displayList[i]=null;}}}if(displayData!==null){var rawDisplayDatas=slot.rawDisplayDatas;var rawDisplayData=null;if(rawDisplayDatas){if(dragonBones.DragonBones.webAssembly){if(displayIndex<rawDisplayDatas.size()){rawDisplayData=rawDisplayDatas.get(displayIndex);}}else {if(displayIndex<rawDisplayDatas.length){rawDisplayData=rawDisplayDatas[displayIndex];}}}displayList[displayIndex]=this._getSlotDisplay(null,displayData,rawDisplayData,slot);}else {displayList[displayIndex]=null;}slot.displayList=displayList;};BaseFactory.prototype.replaceSlotDisplay=function(dragonBonesName,armatureName,slotName,displayName,slot,displayIndex){if(displayIndex===void 0){displayIndex=-1;}var armatureData=this.getArmatureData(armatureName,dragonBonesName||"");if(!armatureData||!armatureData.defaultSkin){return false;}var displayData=armatureData.defaultSkin.getDisplay(slotName,displayName);if(!displayData){return false;}this.replaceDisplay(slot,displayData,displayIndex);return true;};BaseFactory.prototype.replaceSlotDisplayList=function(dragonBonesName,armatureName,slotName,slot){var armatureData=this.getArmatureData(armatureName,dragonBonesName||"");if(!armatureData||!armatureData.defaultSkin){return false;}var displays=armatureData.defaultSkin.getDisplays(slotName);if(!displays){return false;}var displayIndex=0;for(var i=0,l=dragonBones.DragonBones.webAssembly?displays.size():displays.length;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displays.get(i):displays[i];this.replaceDisplay(slot,displayData,displayIndex++);}return true;};BaseFactory.prototype.replaceSkin=function(armature,skin,isOverride,exclude){if(isOverride===void 0){isOverride=false;}if(exclude===void 0){exclude=null;}var success=false;var defaultSkin=skin.parent.defaultSkin;for(var _i=0,_a=armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(exclude!==null&&exclude.indexOf(slot.name)>=0){continue;}var displays=skin.getDisplays(slot.name);if(!displays){if(defaultSkin!==null&&skin!==defaultSkin){displays=defaultSkin.getDisplays(slot.name);}if(!displays){if(isOverride){slot.rawDisplayDatas=null;slot.displayList=[];}continue;}}var displayCount=dragonBones.DragonBones.webAssembly?displays.size():displays.length;var displayList=slot.displayList;displayList.length=displayCount;for(var i=0,l=displayCount;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displays.get(i):displays[i];if(displayData!==null){displayList[i]=this._getSlotDisplay(null,displayData,null,slot);}else {displayList[i]=null;}}success=true;slot.rawDisplayDatas=displays;slot.displayList=displayList;}return success;};BaseFactory.prototype.replaceAnimation=function(armature,armatureData,isOverride){if(isOverride===void 0){isOverride=true;}var skinData=armatureData.defaultSkin;if(skinData===null){return false;}if(isOverride){armature.animation.animations=armatureData.animations;}else {var rawAnimations=armature.animation.animations;var animations={};for(var k in rawAnimations){animations[k]=rawAnimations[k];}for(var k in armatureData.animations){animations[k]=armatureData.animations[k];}armature.animation.animations=animations;}for(var _i=0,_a=armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];var index=0;for(var _b=0,_c=slot.displayList;_b<_c.length;_b++){var display=_c[_b];if(display instanceof dragonBones.Armature){var displayDatas=skinData.getDisplays(slot.name);if(displayDatas!==null&&index<(dragonBones.DragonBones.webAssembly?displayDatas.size():displayDatas.length)){var displayData=dragonBones.DragonBones.webAssembly?displayDatas.get(index):displayDatas[index];if(displayData!==null&&displayData.type===1){var childArmatureData=this.getArmatureData(displayData.path,displayData.parent.parent.parent.name);if(childArmatureData){this.replaceAnimation(display,childArmatureData,isOverride);}}}}index++;}}return true;};BaseFactory.prototype.getAllDragonBonesData=function(){return this._dragonBonesDataMap;};BaseFactory.prototype.getAllTextureAtlasData=function(){return this._textureAtlasDataMap;};Object.defineProperty(BaseFactory.prototype,"clock",{get:function(){return this._dragonBones.clock;},enumerable:true,configurable:true});Object.defineProperty(BaseFactory.prototype,"dragonBones",{get:function(){return this._dragonBones;},enumerable:true,configurable:true});BaseFactory.prototype.changeSkin=function(armature,skin,exclude){if(exclude===void 0){exclude=null;}return this.replaceSkin(armature,skin,false,exclude);};BaseFactory.prototype.copyAnimationsToArmature=function(toArmature,fromArmatreName,fromSkinName,fromDragonBonesDataName,replaceOriginalAnimation){if(fromDragonBonesDataName===void 0){fromDragonBonesDataName="";}if(replaceOriginalAnimation===void 0){replaceOriginalAnimation=true;}var armatureData=this.getArmatureData(fromArmatreName,fromDragonBonesDataName);if(!armatureData){return false;}return this.replaceAnimation(toArmature,armatureData,replaceOriginalAnimation);};BaseFactory._objectParser=null;BaseFactory._binaryParser=null;return BaseFactory;}();dragonBones.BaseFactory=BaseFactory;var BuildArmaturePackage=function(){function BuildArmaturePackage(){this.dataName="";this.textureAtlasName="";this.skin=null;}return BuildArmaturePackage;}();dragonBones.BuildArmaturePackage=BuildArmaturePackage;})(dragonBones$1||(dragonBones$1={}));(function(dragonBones){dragonBones.BinaryOffset={WeigthBoneCount:0,WeigthFloatOffset:1,WeigthBoneIndices:2,MeshVertexCount:0,MeshTriangleCount:1,MeshFloatOffset:2,MeshWeightOffset:3,MeshVertexIndices:4,TimelineScale:0,TimelineOffset:1,TimelineKeyFrameCount:2,TimelineFrameValueCount:3,TimelineFrameValueOffset:4,TimelineFrameOffset:5,FramePosition:0,FrameTweenType:1,FrameTweenEasingOrCurveSampleCount:2,FrameCurveSamples:3,DeformMeshOffset:0,DeformCount:1,DeformValueCount:2,DeformValueOffset:3,DeformFloatOffset:4};dragonBones.ArmatureType={Armature:0,MovieClip:1,Stage:2};dragonBones.BoneType={Bone:0,Surface:1};dragonBones.DisplayType={Image:0,Armature:1,Mesh:2,BoundingBox:3};dragonBones.BoundingBoxType={Rectangle:0,Ellipse:1,Polygon:2};dragonBones.ActionType={Play:0,Stop:1,GotoAndPlay:2,GotoAndStop:3,FadeIn:4,FadeOut:5,Frame:10,Sound:11};dragonBones.BlendMode={Normal:0,Add:1,Alpha:2,Darken:3,Difference:4,Erase:5,HardLight:6,Invert:7,Layer:8,Lighten:9,Multiply:10,Overlay:11,Screen:12,Subtract:13};dragonBones.TweenType={None:0,Line:1,Curve:2,QuadIn:3,QuadOut:4,QuadInOut:5};dragonBones.TimelineType={Action:0,ZOrder:1,BoneAll:10,BoneTranslate:11,BoneRotate:12,BoneScale:13,Surface:50,SlotDisplay:20,SlotColor:21,SlotFFD:22,IKConstraint:30,AnimationTime:40,AnimationWeight:41};})(dragonBones$1||(dragonBones$1={}));const DragonBones=dragonBones$1.DragonBones;const BaseObject$1=dragonBones$1.BaseObject;const Matrix$1=dragonBones$1.Matrix;dragonBones$1.Transform;dragonBones$1.ColorTransform;dragonBones$1.Point;dragonBones$1.Rectangle;dragonBones$1.UserData;dragonBones$1.ActionData;dragonBones$1.DragonBonesData;dragonBones$1.ArmatureData;dragonBones$1.BoneData;dragonBones$1.SurfaceData;dragonBones$1.SlotData;dragonBones$1.ConstraintData;dragonBones$1.IKConstraintData;dragonBones$1.PathConstraintData;dragonBones$1.CanvasData;dragonBones$1.SkinData;dragonBones$1.VerticesData;const DisplayData=dragonBones$1.DisplayData;dragonBones$1.ImageDisplayData;dragonBones$1.ArmatureDisplayData;dragonBones$1.MeshDisplayData;dragonBones$1.BoundingBoxDisplayData;dragonBones$1.PathDisplayData;dragonBones$1.WeightData;dragonBones$1.BoundingBoxData;dragonBones$1.RectangleBoundingBoxData;dragonBones$1.EllipseBoundingBoxData;dragonBones$1.PolygonBoundingBoxData;dragonBones$1.AnimationData;dragonBones$1.TimelineData;dragonBones$1.AnimationConfig;const TextureAtlasData$1=dragonBones$1.TextureAtlasData;const TextureData$1=dragonBones$1.TextureData;dragonBones$1.DeformVertices;const Armature$1=dragonBones$1.Armature;dragonBones$1.TransformObject;dragonBones$1.Bone;dragonBones$1.Surface;const Slot$1=dragonBones$1.Slot;dragonBones$1.Constraint;dragonBones$1.IKConstraint;dragonBones$1.PathConstraint;dragonBones$1.WorldClock;const Animation$1=dragonBones$1.Animation;dragonBones$1.AnimationState;dragonBones$1.BonePose;dragonBones$1.BlendState;dragonBones$1.TimelineState;dragonBones$1.TweenTimelineState;dragonBones$1.BoneTimelineState;dragonBones$1.SlotTimelineState;dragonBones$1.ConstraintTimelineState;dragonBones$1.ActionTimelineState;dragonBones$1.ZOrderTimelineState;dragonBones$1.BoneAllTimelineState;dragonBones$1.BoneTranslateTimelineState;dragonBones$1.BoneRotateTimelineState;dragonBones$1.BoneScaleTimelineState;dragonBones$1.SurfaceTimelineState;dragonBones$1.SlotDislayTimelineState;dragonBones$1.SlotColorTimelineState;dragonBones$1.DeformTimelineState;dragonBones$1.IKConstraintTimelineState;dragonBones$1.AnimationTimelineState;const EventObject$1=dragonBones$1.EventObject;dragonBones$1.DataParser;dragonBones$1.ObjectDataParser;dragonBones$1.ActionFrame;dragonBones$1.BinaryDataParser;const BaseFactory$1=dragonBones$1.BaseFactory;dragonBones$1.BuildArmaturePackage;const BinaryOffset=dragonBones$1.BinaryOffset;dragonBones$1.ArmatureType;const BoneType=dragonBones$1.BoneType;dragonBones$1.DisplayType;dragonBones$1.BoundingBoxType;dragonBones$1.ActionType;dragonBones$1.BlendMode;dragonBones$1.TweenType;dragonBones$1.TimelineType;

      var _dec$X, _class$W, _dec2$N, _class3$i;
      const {
        ccclass: ccclass$n
      } = _decorator;
      let CCTextureAtlasData$1 = (_dec$X = ccclass$n('dragonBones.CCTextureAtlasData'), _dec$X(_class$W = class CCTextureAtlasData extends TextureAtlasData$1 {
        constructor(...args) {
          super(...args);
          this._renderTexture = null;
        }
        get renderTexture() {
          return this._renderTexture;
        }
        set renderTexture(value) {
          this._renderTexture = value;
          if (value) {
            for (const k in this.textures) {
              const textureData = this.textures[k];
              if (!textureData.spriteFrame) {
                let rect = null;
                if (textureData.rotated) {
                  rect = new Rect$1(textureData.region.x, textureData.region.y, textureData.region.height, textureData.region.width);
                } else {
                  rect = new Rect$1(textureData.region.x, textureData.region.y, textureData.region.width, textureData.region.height);
                  textureData.spriteFrame = new SpriteFrame();
                  textureData.spriteFrame.texture = value;
                  textureData.spriteFrame.rect = rect;
                }
              }
            }
          } else {
            for (const k in this.textures) {
              const textureData = this.textures[k];
              textureData.spriteFrame = null;
            }
          }
        }
        static toString() {
          return '[class dragonBones.CCTextureAtlasData]';
        }
        createTexture() {
          return BaseObject$1.borrowObject(CCTextureData$1);
        }
        _onClear() {
          super._onClear();
          this.renderTexture = null;
        }
      }) || _class$W);
      let CCTextureData$1 = (_dec2$N = ccclass$n('dragonBones.CCTextureData'), _dec2$N(_class3$i = class CCTextureData extends TextureData$1 {
        constructor(...args) {
          super(...args);
          this.spriteFrame = null;
        }
        static toString() {
          return '[class dragonBones.CCTextureData]';
        }
        _onClear() {
          super._onClear();
          this.spriteFrame = null;
        }
      }) || _class3$i);

      var _dec$W, _class$V;
      const {
        ccclass: ccclass$m
      } = _decorator;
      let CCSlot$1 = (_dec$W = ccclass$m('dragonBones.CCSlot'), _dec$W(_class$V = class CCSlot extends Slot$1 {
        static toString() {
          return '[class dragonBones.CCSlot]';
        }
        constructor() {
          super();
          this._localVertices = void 0;
          this._indices = void 0;
          this._matrix = void 0;
          this._worldMatrix = void 0;
          this._worldMatrixDirty = void 0;
          this._color = void 0;
          this._localVertices = [];
          this._indices = [];
          this._matrix = new Mat4();
          this._worldMatrix = new Mat4();
          this._worldMatrixDirty = true;
          this._visible = false;
          this._color = new Color$1();
        }
        getTexture() {
          if (this._textureData) {
            const sp = this._textureData.spriteFrame;
            const tex = sp.texture;
            return tex;
          }
          return null;
        }
        calculWorldMatrix() {
          const parent = this._armature._parent;
          if (parent) {
            this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix);
          } else {
            Mat4.copy(this._worldMatrix, this._matrix);
          }
          this._worldMatrixDirty = false;
        }
        _onClear() {
          super._onClear();
          this._localVertices.length = 0;
          this._indices.length = 0;
          Mat4.identity(this._matrix);
          Mat4.identity(this._worldMatrix);
          this._worldMatrixDirty = true;
          this._color = new Color$1();
          this._visible = false;
        }
        _onUpdateDisplay() {}
        _initDisplay(value) {}
        _addDisplay() {
          this._visible = true;
        }
        _replaceDisplay(value) {}
        _removeDisplay() {
          this._visible = false;
        }
        _disposeDisplay(object) {}
        _updateVisible() {
          this._visible = this.parent.visible;
        }
        _updateGlueMesh() {}
        _updateZOrder() {}
        _updateBlendMode() {
          if (this._childArmature) {
            const childSlots = this._childArmature.getSlots();
            for (let i = 0, l = childSlots.length; i < l; i++) {
              const slot = childSlots[i];
              slot._blendMode = this._blendMode;
              slot._updateBlendMode();
            }
          }
        }
        _updateColor() {
          const c = this._color;
          c.r = this._colorTransform.redMultiplier * 255;
          c.g = this._colorTransform.greenMultiplier * 255;
          c.b = this._colorTransform.blueMultiplier * 255;
          c.a = this._colorTransform.alphaMultiplier * 255;
        }
        _updateFrame() {
          this._indices.length = 0;
          const indices = this._indices;
          const localVertices = this._localVertices;
          let indexOffset = 0;
          let vfOffset = 0;
          const currentTextureData = this._textureData;
          if (!this._display || this._displayIndex < 0 || !currentTextureData || !currentTextureData.spriteFrame) return;
          const texture = currentTextureData.spriteFrame.texture;
          const textureAtlasWidth = texture.width;
          const textureAtlasHeight = texture.height;
          const region = currentTextureData.region;
          if (textureAtlasWidth === 0 || textureAtlasHeight === 0) {
            console.error(`SpriteFrame ${currentTextureData.spriteFrame.name} incorrect size ${textureAtlasWidth} x ${textureAtlasHeight}`);
            return;
          }
          const currentVerticesData = this._deformVertices !== null && this._display === this._meshDisplay ? this._deformVertices.verticesData : null;
          if (currentVerticesData) {
            const data = currentVerticesData.data;
            const intArray = data.intArray;
            const floatArray = data.floatArray;
            const vertexCount = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexCount];
            const triangleCount = intArray[currentVerticesData.offset + BinaryOffset.MeshTriangleCount];
            let vertexOffset = intArray[currentVerticesData.offset + BinaryOffset.MeshFloatOffset];
            if (vertexOffset < 0) {
              vertexOffset += 65536;
            }
            const uvOffset = vertexOffset + vertexCount * 2;
            const scale = this._armature._armatureData.scale;
            for (let i = 0, l = vertexCount * 2; i < l; i += 2) {
              localVertices[vfOffset++] = floatArray[vertexOffset + i] * scale;
              localVertices[vfOffset++] = -floatArray[vertexOffset + i + 1] * scale;
              if (currentVerticesData.rotated) {
                localVertices[vfOffset++] = (region.x + (1.0 - floatArray[uvOffset + i]) * region.width) / textureAtlasWidth;
                localVertices[vfOffset++] = (region.y + floatArray[uvOffset + i + 1] * region.height) / textureAtlasHeight;
              } else {
                localVertices[vfOffset++] = (region.x + floatArray[uvOffset + i] * region.width) / textureAtlasWidth;
                localVertices[vfOffset++] = (region.y + floatArray[uvOffset + i + 1] * region.height) / textureAtlasHeight;
              }
            }
            for (let i = 0; i < triangleCount * 3; ++i) {
              indices[indexOffset++] = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexIndices + i];
            }
            localVertices.length = vfOffset;
            indices.length = indexOffset;
            const isSkinned = !!currentVerticesData.weight;
            if (isSkinned) {
              this._identityTransform();
            }
          } else {
            const l = region.x / textureAtlasWidth;
            const b = (region.y + region.height) / textureAtlasHeight;
            const r = (region.x + region.width) / textureAtlasWidth;
            const t = region.y / textureAtlasHeight;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = l;
            localVertices[vfOffset++] = b;
            localVertices[vfOffset++] = region.width;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = r;
            localVertices[vfOffset++] = b;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = region.height;
            localVertices[vfOffset++] = l;
            localVertices[vfOffset++] = t;
            localVertices[vfOffset++] = region.width;
            localVertices[vfOffset++] = region.height;
            localVertices[vfOffset++] = r;
            localVertices[vfOffset++] = t;
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 1;
            indices[4] = 3;
            indices[5] = 2;
            localVertices.length = vfOffset;
            indices.length = 6;
          }
          this._visibleDirty = true;
          this._blendModeDirty = true;
          this._colorDirty = true;
        }
        _updateMesh() {
          const scale = this._armature._armatureData.scale;
          const deformVertices = this._deformVertices.vertices;
          const bones = this._deformVertices.bones;
          const verticesData = this._deformVertices.verticesData;
          const weightData = verticesData.weight;
          const hasDeform = deformVertices.length > 0 && verticesData.inheritDeform;
          const localVertices = this._localVertices;
          if (weightData) {
            const data = verticesData.data;
            const intArray = data.intArray;
            const floatArray = data.floatArray;
            const vertexCount = intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
            let weightFloatOffset = intArray[weightData.offset + BinaryOffset.WeigthFloatOffset];
            if (weightFloatOffset < 0) {
              weightFloatOffset += 65536;
            }
            for (let i = 0, iB = weightData.offset + BinaryOffset.WeigthBoneIndices + bones.length, iV = weightFloatOffset, iF = 0, lvi = 0; i < vertexCount; i++, lvi += 4) {
              const boneCount = intArray[iB++];
              let xG = 0.0;
              let yG = 0.0;
              for (let j = 0; j < boneCount; ++j) {
                const boneIndex = intArray[iB++];
                const bone = bones[boneIndex];
                if (bone !== null) {
                  const matrix = bone.globalTransformMatrix;
                  const weight = floatArray[iV++];
                  let xL = floatArray[iV++] * scale;
                  let yL = floatArray[iV++] * scale;
                  if (hasDeform) {
                    xL += deformVertices[iF++];
                    yL += deformVertices[iF++];
                  }
                  xG += (matrix.a * xL + matrix.c * yL + matrix.tx) * weight;
                  yG += (matrix.b * xL + matrix.d * yL + matrix.ty) * weight;
                }
              }
              localVertices[lvi] = xG;
              localVertices[lvi + 1] = -yG;
            }
          } else if (hasDeform) {
            const isSurface = this._parent._boneData.type !== BoneType.Bone;
            const data = verticesData.data;
            const intArray = data.intArray;
            const floatArray = data.floatArray;
            const vertexCount = intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
            let vertexOffset = intArray[verticesData.offset + BinaryOffset.MeshFloatOffset];
            if (vertexOffset < 0) {
              vertexOffset += 65536;
            }
            for (let i = 0, l = vertexCount, lvi = 0; i < l; i++, lvi += 4) {
              const x = floatArray[vertexOffset + i * 2] * scale + deformVertices[i * 2];
              const y = floatArray[vertexOffset + i * 2 + 1] * scale + deformVertices[i * 2 + 1];
              if (isSurface) {
                const matrix = this._parent._getGlobalTransformMatrix(x, y);
                localVertices[lvi] = matrix.a * x + matrix.c * y + matrix.tx;
                localVertices[lvi + 1] = -matrix.b * x + matrix.d * y + matrix.ty;
              } else {
                localVertices[lvi] = x;
                localVertices[lvi + 1] = -y;
              }
            }
          }
          if (weightData) {
            this._identityTransform();
          }
        }
        _identityTransform() {
          const m = this._matrix;
          m.m00 = 1.0;
          m.m01 = 0.0;
          m.m04 = -0.0;
          m.m05 = -1.0;
          m.m12 = 0.0;
          m.m13 = 0.0;
          this._worldMatrixDirty = true;
        }
        _updateTransform() {
          const m = this._matrix;
          m.m00 = this.globalTransformMatrix.a;
          m.m01 = this.globalTransformMatrix.b;
          m.m04 = -this.globalTransformMatrix.c;
          m.m05 = -this.globalTransformMatrix.d;
          if (this._childArmature) {
            m.m12 = this.globalTransformMatrix.tx;
            m.m13 = this.globalTransformMatrix.ty;
          } else {
            m.m12 = this.globalTransformMatrix.tx - (this.globalTransformMatrix.a * this._pivotX - this.globalTransformMatrix.c * this._pivotY);
            m.m13 = this.globalTransformMatrix.ty - (this.globalTransformMatrix.b * this._pivotX - this.globalTransformMatrix.d * this._pivotY);
          }
          this._worldMatrixDirty = true;
        }
        updateWorldMatrix() {
          if (!this._armature) return;
          const parentSlot = this._armature._parent;
          if (parentSlot) {
            parentSlot.updateWorldMatrix();
          }
          if (this._worldMatrixDirty) {
            this.calculWorldMatrix();
            const childArmature = this.childArmature;
            if (!childArmature) return;
            const slots = childArmature.getSlots();
            for (let i = 0, n = slots.length; i < n; i++) {
              const slot = slots[i];
              if (slot) {
                slot._worldMatrixDirty = true;
              }
            }
          }
        }
        _mulMat(out, a, b) {
          const aa = a.m00;
          const ab = a.m01;
          const ac = a.m04;
          const ad = a.m05;
          const atx = a.m12;
          const aty = a.m13;
          const ba = b.m00;
          const bb = b.m01;
          const bc = b.m04;
          const bd = b.m05;
          const btx = b.m12;
          const bty = b.m13;
          if (ab !== 0 || ac !== 0) {
            out.m00 = ba * aa + bb * ac;
            out.m01 = ba * ab + bb * ad;
            out.m04 = bc * aa + bd * ac;
            out.m05 = bc * ab + bd * ad;
            out.m12 = aa * btx + ac * bty + atx;
            out.m13 = ab * btx + ad * bty + aty;
          } else {
            out.m00 = ba * aa;
            out.m01 = bb * ad;
            out.m04 = bc * aa;
            out.m05 = bd * ad;
            out.m12 = aa * btx + atx;
            out.m13 = ad * bty + aty;
          }
        }
      }) || _class$V);

      var _dec$V, _class$U;
      const {
        ccclass: ccclass$l
      } = _decorator;
      let CCArmatureDisplay$1 = (_dec$V = ccclass$l('dragonBones.CCArmatureDisplay'), _dec$V(_class$U = class CCArmatureDisplay extends DisplayData {
        get node() {
          return this;
        }
        constructor() {
          super();
          this.shouldAdvanced = false;
          this._ccNode = null;
          this._ccComponent = null;
          this._eventTarget = void 0;
          this._armature = null;
          this._eventTarget = new EventTarget();
        }
        hasEvent(type) {
          warn('Method not implemented.');
          return false;
        }
        addEvent(type, listener, thisObject) {
          warn('Method not implemented.');
        }
        removeEvent(type, listener, thisObject) {
          warn('Method not implemented.');
        }
        setEventTarget(eventTarget) {
          this._eventTarget = eventTarget;
        }
        getRootDisplay() {
          let parentSlot = this._armature._parent;
          if (!parentSlot) {
            return this;
          }
          let slot;
          while (parentSlot) {
            slot = parentSlot;
            parentSlot = parentSlot._armature._parent;
          }
          return slot._armature.display;
        }
        convertToRootSpace(pos) {
          const slot = this._armature._parent;
          if (!slot) {
            return pos;
          }
          slot.updateWorldMatrix();
          const worldMatrix = slot._worldMatrix;
          const newPos = new Vec3(0, 0);
          newPos.x = pos.x * worldMatrix.m00 + pos.y * worldMatrix.m04 + worldMatrix.m12;
          newPos.y = pos.x * worldMatrix.m01 + pos.y * worldMatrix.m05 + worldMatrix.m13;
          return newPos;
        }
        convertToWorldSpace(point) {
          var _ccNode$_uiProps$uiTr;
          const newPos = this.convertToRootSpace(point);
          const ccNode = this.getRootNode();
          return ccNode === null || ccNode === void 0 ? void 0 : (_ccNode$_uiProps$uiTr = ccNode._uiProps.uiTransformComp) === null || _ccNode$_uiProps$uiTr === void 0 ? void 0 : _ccNode$_uiProps$uiTr.convertToWorldSpaceAR(newPos);
        }
        getRootNode() {
          const rootDisplay = this.getRootDisplay();
          return rootDisplay && rootDisplay._ccNode;
        }
        dbInit(armature) {
          this._armature = armature;
        }
        dbClear() {
          this._armature = null;
        }
        dbUpdate() {
          if (this._ccComponent) {
            this._ccComponent.markForUpdateRenderData();
          }
        }
        advanceTimeBySelf(on) {
          this.shouldAdvanced = !!on;
        }
        hasDBEventListener(type) {
          return this._eventTarget.hasEventListener(type);
        }
        addDBEventListener(type, listener, target) {
          this._eventTarget.on(type, listener, target);
        }
        removeDBEventListener(type, listener, target) {
          this._eventTarget.off(type, listener, target);
        }
        dispatchDBEvent(type, eventObject) {
          this._eventTarget.emit(type, eventObject);
        }
      }) || _class$U);

      var _dec$U, _class$T, _class2$P;
      const {
        ccclass: ccclass$k
      } = _decorator;
      let CCFactory$1 = (_dec$U = ccclass$k('CCFactory'), _dec$U(_class$T = (_class2$P = class CCFactory extends BaseFactory$1 {
        static getInstance() {
          if (!CCFactory._factory) {
            CCFactory._factory = new CCFactory();
          }
          return CCFactory._factory;
        }
        constructor() {
          super();
          this.id = void 0;
          this.uuid = void 0;
          this._slots = void 0;
          const eventManager = new CCArmatureDisplay$1();
          this._dragonBones = new DragonBones(eventManager);
          if (director.getScheduler()) {
            game.on(Game.EVENT_RESTART, this.onRestart, this);
            this.initUpdate();
          }
          this.id = this.uuid = 'CCFactory';
        }
        onRestart() {
          CCFactory._factory = null;
        }
        initUpdate(dt) {
          Scheduler.enableForTarget(this);
          director.getScheduler().scheduleUpdate(this, System.Priority.HIGH, false);
        }
        update(dt) {
          this._dragonBones.advanceTime(dt);
        }
        getDragonBonesDataByRawData(rawData) {
          const dataParser = rawData instanceof ArrayBuffer ? BaseFactory$1._binaryParser : this._dataParser;
          return dataParser.parseDragonBonesData(rawData, 1.0);
        }
        buildArmatureDisplay(armatureName, dragonBonesName, skinName, textureAtlasName) {
          const armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName);
          return armature ? armature._display : null;
        }
        createArmatureNode(comp, armatureName, node) {
          node = node || new Node$1();
          let display = node.getComponent('dragonBones.ArmatureDisplay');
          if (!display) {
            display = node.addComponent('dragonBones.ArmatureDisplay');
          }
          node.name = armatureName;
          display._armatureName = armatureName;
          display._dragonAsset = comp.dragonAsset;
          display._dragonAtlasAsset = comp.dragonAtlasAsset;
          display._init();
          return display;
        }
        _buildTextureAtlasData(textureAtlasData, textureAtlas) {
          if (textureAtlasData) {
            textureAtlasData.renderTexture = textureAtlas;
          } else {
            textureAtlasData = BaseObject$1.borrowObject(CCTextureAtlasData$1);
          }
          return textureAtlasData;
        }
        _sortSlots() {
          const slots = this._slots;
          const sortedSlots = [];
          for (let i = 0, l = slots.length; i < l; i++) {
            const slot = slots[i];
            const zOrder = slot._zOrder;
            let inserted = false;
            for (let j = sortedSlots.length - 1; j >= 0; j--) {
              if (zOrder >= sortedSlots[j]._zOrder) {
                sortedSlots.splice(j + 1, 0, slot);
                inserted = true;
                break;
              }
            }
            if (!inserted) {
              sortedSlots.unshift(slot);
            }
          }
          this._slots = sortedSlots;
        }
        _buildArmature(dataPackage) {
          const armature = BaseObject$1.borrowObject(Armature$1);
          armature._skinData = dataPackage.skin;
          armature._animation = BaseObject$1.borrowObject(Animation$1);
          armature._animation._armature = armature;
          armature._animation.animations = dataPackage.armature.animations;
          armature._isChildArmature = false;
          const display = new CCArmatureDisplay$1();
          armature.init(dataPackage.armature, display, display, this._dragonBones);
          return armature;
        }
        _buildSlot(dataPackage, slotData, displays) {
          const slot = BaseObject$1.borrowObject(CCSlot$1);
          const display = slot;
          slot.init(slotData, displays, display, display);
          return slot;
        }
        getDragonBonesDataByUUID(uuid) {
          for (const name in this._dragonBonesDataMap) {
            if (name.indexOf(uuid) !== -1) {
              return this._dragonBonesDataMap[name];
            }
          }
          return null;
        }
        removeDragonBonesDataByUUID(uuid, disposeData) {
          if (disposeData === undefined) {
            disposeData = true;
          }
          for (const name in this._dragonBonesDataMap) {
            if (name.indexOf(uuid) === -1) continue;
            if (disposeData) {
              this._dragonBones.bufferObject(this._dragonBonesDataMap[name]);
            }
            delete this._dragonBonesDataMap[name];
          }
        }
      }, _class2$P._factory = null, _class2$P)) || _class$T);

      var _class2$O;
      const MaxCacheTime$1 = 30;
      const FrameTime$1 = 1 / 60;
      const _vertices = [];
      const _indices = [];
      let _boneInfoOffset = 0;
      let _indexOffset$1 = 0;
      let _vfOffset$1 = 0;
      let _preTexUrl = null;
      let _preBlendMode = null;
      let _segVCount = 0;
      let _segICount = 0;
      let _segOffset = 0;
      let _colorOffset = 0;
      let _preColor = 0;
      let _x;
      let _y;
      const PER_VERTEX_SIZE$1 = 5;
      const EXPORT_VERTEX_SIZE = 9;
      let AnimationCache$1 = class AnimationCache {
        constructor() {
          this.maxVertexCount = 0;
          this.maxIndexCount = 0;
          this._privateMode = false;
          this._inited = false;
          this._invalid = true;
          this._enableCacheAttachedInfo = false;
          this.frames = [];
          this.totalTime = 0;
          this.isCompleted = false;
          this._frameIdx = -1;
          this._armatureInfo = null;
          this._animationName = null;
          this._tempSegments = null;
          this._tempColors = null;
          this._tempBoneInfos = null;
        }
        init(armatureInfo, animationName) {
          this._inited = true;
          this._armatureInfo = armatureInfo;
          this._animationName = animationName;
        }
        clear() {
          this._inited = false;
          for (let i = 0, n = this.frames.length; i < n; i++) {
            const frame = this.frames[i];
            frame.segments.length = 0;
          }
          this.invalidAllFrame();
        }
        begin() {
          if (!this._invalid) return;
          const armatureInfo = this._armatureInfo;
          const curAnimationCache = armatureInfo.curAnimationCache;
          if (curAnimationCache && curAnimationCache !== this) {
            if (this._privateMode) {
              curAnimationCache.invalidAllFrame();
            } else {
              curAnimationCache.updateToFrame();
            }
          }
          const armature = armatureInfo.armature;
          const animation = armature.animation;
          animation.play(this._animationName, 1);
          armatureInfo.curAnimationCache = this;
          this._invalid = false;
          this._frameIdx = -1;
          this.totalTime = 0;
          this.isCompleted = false;
        }
        end() {
          if (!this._needToUpdate()) {
            this._armatureInfo.curAnimationCache = null;
            this.frames.length = this._frameIdx + 1;
            this.isCompleted = true;
          }
        }
        _needToUpdate(toFrameIdx) {
          const armatureInfo = this._armatureInfo;
          const armature = armatureInfo.armature;
          const animation = armature.animation;
          return !animation.isCompleted && this.totalTime < MaxCacheTime$1 && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
        }
        updateToFrame(toFrameIdx) {
          if (!this._inited) return;
          this.begin();
          if (!this._needToUpdate(toFrameIdx)) return;
          const armatureInfo = this._armatureInfo;
          const armature = armatureInfo.armature;
          do {
            armature.advanceTime(FrameTime$1);
            this._frameIdx++;
            this.updateFrame(armature, this._frameIdx);
            this.totalTime += FrameTime$1;
          } while (this._needToUpdate(toFrameIdx));
          this.end();
        }
        isInited() {
          return this._inited;
        }
        isInvalid() {
          return this._invalid;
        }
        invalidAllFrame() {
          this.isCompleted = false;
          this._invalid = true;
        }
        updateAllFrame() {
          this.invalidAllFrame();
          this.updateToFrame();
        }
        enableCacheAttachedInfo() {
          if (!this._enableCacheAttachedInfo) {
            this._enableCacheAttachedInfo = true;
            this.invalidAllFrame();
          }
        }
        updateFrame(armature, index) {
          _vfOffset$1 = 0;
          _boneInfoOffset = 0;
          _indexOffset$1 = 0;
          _preTexUrl = null;
          _preBlendMode = null;
          _segVCount = 0;
          _segICount = 0;
          _segOffset = 0;
          _colorOffset = 0;
          _preColor = 0;
          this.frames[index] = this.frames[index] || {
            segments: [],
            colors: [],
            boneInfos: [],
            vertices: new Float32Array(),
            uintVert: new Uint32Array(),
            indices: new Uint16Array()
          };
          const frame = this.frames[index];
          const segments = this._tempSegments = frame.segments;
          const colors = this._tempColors = frame.colors;
          const boneInfos = this._tempBoneInfos = frame.boneInfos;
          this._traverseArmature(armature, 1.0);
          if (_colorOffset > 0) {
            colors[_colorOffset - 1].vfOffset = _vfOffset$1;
          }
          colors.length = _colorOffset;
          boneInfos.length = _boneInfoOffset;
          const preSegOffset = _segOffset - 1;
          if (preSegOffset >= 0) {
            if (_segICount > 0) {
              const preSegInfo = segments[preSegOffset];
              preSegInfo.indexCount = _segICount;
              preSegInfo.vfCount = _segVCount * EXPORT_VERTEX_SIZE;
              preSegInfo.vertexCount = _segVCount;
              segments.length = _segOffset;
            } else {
              segments.length = _segOffset - 1;
            }
          }
          if (segments.length === 0) return;
          let vertices = frame.vertices;
          const vertexCount = _vfOffset$1 / PER_VERTEX_SIZE$1;
          const copyOutVerticeSize = vertexCount * EXPORT_VERTEX_SIZE;
          if (!vertices || vertices.length < _vfOffset$1) {
            vertices = frame.vertices = new Float32Array(copyOutVerticeSize);
          }
          let colorI32;
          for (let i = 0, j = 0; i < copyOutVerticeSize;) {
            vertices[i] = _vertices[j++];
            vertices[i + 1] = _vertices[j++];
            vertices[i + 3] = _vertices[j++];
            vertices[i + 4] = _vertices[j++];
            colorI32 = _vertices[j++];
            vertices[i + 5] = (colorI32 & 0xff) / 255.0;
            vertices[i + 6] = (colorI32 >> 8 & 0xff) / 255.0;
            vertices[i + 7] = (colorI32 >> 16 & 0xff) / 255.0;
            vertices[i + 8] = (colorI32 >> 24 & 0xff) / 255.0;
            i += EXPORT_VERTEX_SIZE;
          }
          let indices = frame.indices;
          if (!indices || indices.length < _indexOffset$1) {
            indices = frame.indices = new Uint16Array(_indexOffset$1);
          }
          for (let i = 0; i < _indexOffset$1; i++) {
            indices[i] = _indices[i];
          }
          frame.vertices = vertices;
          frame.indices = indices;
          this.maxVertexCount = vertexCount > this.maxVertexCount ? vertexCount : this.maxVertexCount;
          this.maxIndexCount = indices.length > this.maxIndexCount ? indices.length : this.maxIndexCount;
        }
        _traverseArmature(armature, parentOpacity) {
          const colors = this._tempColors;
          const segments = this._tempSegments;
          const boneInfos = this._tempBoneInfos;
          const slots = armature._slots;
          let slotVertices;
          let slotIndices;
          let slot;
          let slotMatrix;
          let slotColor;
          let colorVal;
          let texture;
          let preSegOffset;
          let preSegInfo;
          const bones = armature._bones;
          if (this._enableCacheAttachedInfo) {
            for (let i = 0, l = bones.length; i < l; i++, _boneInfoOffset++) {
              const bone = bones[i];
              let boneInfo = boneInfos[_boneInfoOffset];
              if (!boneInfo) {
                boneInfo = boneInfos[_boneInfoOffset] = {
                  globalTransformMatrix: new Matrix$1()
                };
              }
              const boneMat = bone.globalTransformMatrix;
              const cacheBoneMat = boneInfo.globalTransformMatrix;
              cacheBoneMat.copyFrom(boneMat);
            }
          }
          for (let i = 0, l = slots.length; i < l; i++) {
            slot = slots[i];
            if (!slot._visible || !slot._displayData) continue;
            slot.updateWorldMatrix();
            slotColor = slot._color;
            if (slot.childArmature) {
              this._traverseArmature(slot.childArmature, parentOpacity * slotColor.a / 255);
              continue;
            }
            texture = slot.getTexture();
            if (!texture) continue;
            if (_preTexUrl !== texture.nativeUrl || _preBlendMode !== slot._blendMode) {
              _preTexUrl = texture.nativeUrl;
              _preBlendMode = slot._blendMode;
              preSegOffset = _segOffset - 1;
              if (preSegOffset >= 0) {
                if (_segICount > 0) {
                  preSegInfo = segments[preSegOffset];
                  preSegInfo.indexCount = _segICount;
                  preSegInfo.vertexCount = _segVCount;
                  preSegInfo.vfCount = _segVCount * EXPORT_VERTEX_SIZE;
                } else {
                  _segOffset--;
                }
              }
              segments[_segOffset] = {
                tex: texture,
                blendMode: slot._blendMode,
                indexCount: 0,
                vertexCount: 0,
                vfCount: 0
              };
              _segOffset++;
              _segICount = 0;
              _segVCount = 0;
            }
            colorVal = (slotColor.a * parentOpacity << 24 >>> 0) + (slotColor.b << 16) + (slotColor.g << 8) + slotColor.r;
            if (_preColor !== colorVal) {
              _preColor = colorVal;
              if (_colorOffset > 0) {
                colors[_colorOffset - 1].vfOffset = _vfOffset$1;
              }
              colors[_colorOffset++] = {
                r: slotColor.r,
                g: slotColor.g,
                b: slotColor.b,
                a: slotColor.a * parentOpacity,
                vfOffset: 0
              };
            }
            slotVertices = slot._localVertices;
            slotIndices = slot._indices;
            slotMatrix = slot._worldMatrix;
            for (let j = 0, vl = slotVertices.length; j < vl;) {
              _x = slotVertices[j++];
              _y = slotVertices[j++];
              _vertices[_vfOffset$1++] = _x * slotMatrix.m00 + _y * slotMatrix.m04 + slotMatrix.m12;
              _vertices[_vfOffset$1++] = _x * slotMatrix.m01 + _y * slotMatrix.m05 + slotMatrix.m13;
              _vertices[_vfOffset$1++] = slotVertices[j++];
              _vertices[_vfOffset$1++] = slotVertices[j++];
              _vertices[_vfOffset$1++] = colorVal;
            }
            for (let ii = 0, il = slotIndices.length; ii < il; ii++) {
              _indices[_indexOffset$1++] = _segVCount + slotIndices[ii];
            }
            _segICount += slotIndices.length;
            _segVCount += slotVertices.length / 4;
          }
        }
      };
      class ArmatureCache {
        constructor() {
          this._privateMode = false;
          this._animationPool = {};
          this._armatureCache = {};
        }
        enablePrivateMode() {
          this._privateMode = true;
        }
        dispose() {
          for (const key in this._armatureCache) {
            const armatureInfo = this._armatureCache[key];
            if (armatureInfo) {
              const armature = armatureInfo.armature;
              if (armature) armature.dispose();
            }
          }
          this._armatureCache = {};
          this._animationPool = {};
        }
        _removeArmature(armatureKey) {
          const armatureInfo = this._armatureCache[armatureKey];
          const animationsCache = armatureInfo.animationsCache;
          for (const aniKey in animationsCache) {
            const animationCache = animationsCache[aniKey];
            if (!animationCache) continue;
            this._animationPool[`${armatureKey}#${aniKey}`] = animationCache;
            animationCache.clear();
          }
          const armature = armatureInfo.armature;
          if (armature) armature.dispose();
          delete this._armatureCache[armatureKey];
        }
        resetArmature(uuid) {
          for (const armatureKey in this._armatureCache) {
            if (armatureKey.indexOf(uuid) === -1) continue;
            this._removeArmature(armatureKey);
          }
        }
        getArmatureCache(armatureName, armatureKey, atlasUUID) {
          const armatureInfo = this._armatureCache[armatureKey];
          let armature;
          if (!armatureInfo) {
            const factory = CCFactory$1.getInstance();
            const proxy = factory.buildArmatureDisplay(armatureName, armatureKey, '', atlasUUID);
            if (!proxy || !proxy._armature) return null;
            armature = proxy._armature;
            if (!ArmatureCache.canCache(armature)) {
              armature.dispose();
              return null;
            }
            this._armatureCache[armatureKey] = {
              armature,
              animationsCache: {},
              curAnimationCache: null
            };
          } else {
            armature = armatureInfo.armature;
          }
          return armature;
        }
        getAnimationCache(armatureKey, animationName) {
          const armatureInfo = this._armatureCache[armatureKey];
          if (!armatureInfo) return null;
          const animationsCache = armatureInfo.animationsCache;
          return animationsCache[animationName];
        }
        initAnimationCache(armatureKey, animationName) {
          if (!animationName) return null;
          const armatureInfo = this._armatureCache[armatureKey];
          const armature = armatureInfo && armatureInfo.armature;
          if (!armature) return null;
          const animation = armature.animation;
          const hasAni = animation.hasAnimation(animationName);
          if (!hasAni) return null;
          const animationsCache = armatureInfo.animationsCache;
          let animationCache = animationsCache[animationName];
          if (!animationCache) {
            const poolKey = `${armatureKey}#${animationName}`;
            animationCache = this._animationPool[poolKey];
            if (animationCache) {
              delete this._animationPool[poolKey];
            } else {
              animationCache = new AnimationCache$1();
              animationCache._privateMode = this._privateMode;
            }
            animationCache.init(armatureInfo, animationName);
            animationsCache[animationName] = animationCache;
          }
          return animationCache;
        }
        invalidAnimationCache(armatureKey) {
          const armatureInfo = this._armatureCache[armatureKey];
          const armature = armatureInfo && armatureInfo.armature;
          if (!armature) return;
          const animationsCache = armatureInfo.animationsCache;
          for (const aniKey in animationsCache) {
            const animationCache = animationsCache[aniKey];
            animationCache.invalidAllFrame();
          }
        }
        updateAnimationCache(armatureKey, animationName) {
          if (animationName) {
            const animationCache = this.initAnimationCache(armatureKey, animationName);
            if (!animationCache) return;
            animationCache.updateAllFrame();
          } else {
            const armatureInfo = this._armatureCache[armatureKey];
            const armature = armatureInfo && armatureInfo.armature;
            if (!armature) return;
            const animationsCache = armatureInfo.animationsCache;
            for (const aniKey in animationsCache) {
              const animationCache = animationsCache[aniKey];
              animationCache.updateAllFrame();
            }
          }
        }
        static canCache(armature) {
          const slots = armature._slots;
          for (let i = 0, l = slots.length; i < l; i++) {
            const slot = slots[i];
            if (slot.childArmature) {
              return false;
            }
          }
          return true;
        }
      }
      _class2$O = ArmatureCache;
      ArmatureCache.FrameTime = FrameTime$1;
      ArmatureCache.sharedCache = new _class2$O();

      var _dec$T, _class$S, _class2$N, _initializer$M;
      const {
        ccclass: ccclass$j,
        serializable: serializable$4
      } = _decorator;
      let DragonBonesAsset = (_dec$T = ccclass$j('dragonBones.DragonBonesAsset'), _dec$T(_class$S = (_class2$N = class DragonBonesAsset extends Asset {
        constructor(...args) {
          super(...args);
          this._dragonBonesJson = _initializer$M && _initializer$M();
          this._factory = null;
          this._dragonBonesJsonData = void 0;
          this._armaturesEnum = null;
        }
        get dragonBonesJson() {
          return this._dragonBonesJson;
        }
        set dragonBonesJson(value) {
          this._dragonBonesJson = value;
          this._dragonBonesJsonData = JSON.parse(value);
          this.reset();
        }
        constructctor() {
          this.reset();
        }
        createNode(callback) {
          const node = new Node$1(this.name);
          const armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
          armatureDisplay.dragonAsset = this;
          return callback(null, node);
        }
        reset() {
          this._clear();
        }
        init(factory, atlasUUID) {
          this._factory = factory || CCFactory$1.getInstance();
          if (!this._dragonBonesJsonData && this.dragonBonesJson) {
            this._dragonBonesJsonData = JSON.parse(this.dragonBonesJson);
          }
          let rawData = null;
          if (this._dragonBonesJsonData) {
            rawData = this._dragonBonesJsonData;
          } else {
            rawData = this._nativeAsset;
          }
          if (!this._uuid) {
            const dbData = this._factory.getDragonBonesDataByRawData(rawData);
            if (dbData) {
              this._uuid = dbData.name;
            } else {
              warn('dragonbones name is empty');
            }
          }
          const armatureKey = `${this._uuid}#${atlasUUID}`;
          const dragonBonesData = this._factory.getDragonBonesData(armatureKey);
          if (dragonBonesData) return armatureKey;
          this._factory.parseDragonBonesData(rawData instanceof ArrayBuffer ? rawData : rawData.buffer instanceof ArrayBuffer ? rawData.buffer : rawData, armatureKey);
          return armatureKey;
        }
        getArmatureEnum() {
          if (this._armaturesEnum) {
            return this._armaturesEnum;
          }
          this.init();
          const dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);
          if (dragonBonesData) {
            const armatureNames = dragonBonesData.armatureNames;
            const enumDef = {};
            for (let i = 0; i < armatureNames.length; i++) {
              const name = armatureNames[i];
              enumDef[name] = i;
            }
            return this._armaturesEnum = Enum(enumDef);
          }
          return null;
        }
        getAnimsEnum(armatureName) {
          this.init();
          const dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);
          if (dragonBonesData) {
            const armature = dragonBonesData.getArmature(armatureName);
            if (!armature) {
              return null;
            }
            const enumDef = {
              '<None>': 0
            };
            const anims = armature.animations;
            let i = 0;
            for (const animName in anims) {
              if (anims.hasOwnProperty(animName)) {
                enumDef[animName] = i + 1;
                i++;
              }
            }
            return Enum(enumDef);
          }
          return null;
        }
        destroy() {
          this._clear();
          return super.destroy();
        }
        _clear() {
          if (this._factory) {
            ArmatureCache.sharedCache.resetArmature(this._uuid);
            this._factory.removeDragonBonesDataByUUID(this._uuid, true);
          }
        }
      }, (_initializer$M = applyDecoratedInitializer(_class2$N.prototype, "_dragonBonesJson", [serializable$4], function () {
        return '';
      })), _class2$N)) || _class$S);
      cclegacy.internal.DragonBonesAsset = DragonBonesAsset;

      var _dec$S, _dec2$M, _class$R, _class2$M, _initializer$L, _initializer2$G, _initializer3$y, _initializer4$v;
      const {
        ccclass: ccclass$i,
        serializable: serializable$3,
        type: type$5
      } = _decorator;
      let DragonBonesAtlasAsset = (_dec$S = ccclass$i('dragonBones.DragonBonesAtlasAsset'), _dec2$M = type$5(Texture2D$1), _dec$S(_class$R = (_class2$M = class DragonBonesAtlasAsset extends Asset {
        constructor() {
          super();
          this._atlasJson = _initializer$L && _initializer$L();
          this._texture = _initializer2$G && _initializer2$G();
          this._atlasJsonData = _initializer3$y && _initializer3$y();
          this._factory = null;
          this._textureAtlasData = _initializer4$v && _initializer4$v();
          this._clear();
        }
        get atlasJson() {
          return this._atlasJson;
        }
        set atlasJson(value) {
          this._atlasJson = value;
          this._atlasJsonData = JSON.parse(this.atlasJson);
          this._clear();
        }
        get texture() {
          return this._texture;
        }
        set texture(value) {
          this._texture = value;
          this._clear();
        }
        createNode(callback) {
          const node = new Node$1(this.name);
          const armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
          armatureDisplay.dragonAtlasAsset = this;
          return callback(null, node);
        }
        init(factory) {
          this._factory = factory;
          if (!this._atlasJsonData) {
            this._atlasJsonData = JSON.parse(this.atlasJson);
          }
          const atlasJsonObj = this._atlasJsonData;
          this._uuid = this._uuid || atlasJsonObj.name;
          if (this._textureAtlasData) {
            factory.addTextureAtlasData(this._textureAtlasData, this._uuid);
          } else {
            this._textureAtlasData = factory.parseTextureAtlasData(atlasJsonObj, this.texture, this._uuid);
          }
        }
        destroy() {
          this._clear();
          return super.destroy();
        }
        _clear() {
          return;
        }
      }, (_initializer$L = applyDecoratedInitializer(_class2$M.prototype, "_atlasJson", [serializable$3], function () {
        return '';
      }), _initializer2$G = applyDecoratedInitializer(_class2$M.prototype, "_texture", [serializable$3, _dec2$M], function () {
        return null;
      }), _initializer3$y = applyDecoratedInitializer(_class2$M.prototype, "_atlasJsonData", [serializable$3], function () {
        return {};
      }), _initializer4$v = applyDecoratedInitializer(_class2$M.prototype, "_textureAtlasData", [serializable$3], function () {
        return null;
      })), _class2$M)) || _class$R);
      cclegacy.internal.DragonBonesAtlasAsset = DragonBonesAtlasAsset;

      var _dec$R, _class$Q;
      const _tempMat4 = new Mat4();
      const {
        ccclass: ccclass$h
      } = _decorator;
      let AttachUtil$1 = (_dec$R = ccclass$h('dragonBones.AttachUtil'), _dec$R(_class$Q = class AttachUtil {
        constructor() {
          this._inited = false;
          this._armature = null;
          this._armatureNode = null;
          this._armatureDisplay = null;
        }
        init(armatureDisplay) {
          this._inited = true;
          this._armature = armatureDisplay._armature;
          this._armatureNode = armatureDisplay.node;
          this._armatureDisplay = armatureDisplay;
        }
        reset() {
          this._inited = false;
          this._armature = null;
          this._armatureNode = null;
          this._armatureDisplay = null;
        }
        _syncAttachedNode() {
          if (!this._inited) return;
          this._armatureNode.worldMatrix;
          let boneInfos = null;
          const isCached = this._armatureDisplay.isAnimationCached();
          if (isCached && this._armatureDisplay) {
            boneInfos = this._armatureDisplay._curFrame && this._armatureDisplay._curFrame.boneInfos;
            if (!boneInfos) return;
          }
          const sockets = this._armatureDisplay.sockets;
          const socketNodes = this._armatureDisplay.socketNodes;
          const matrixHandle = (node, boneMat) => {
            const tm = _tempMat4;
            tm.m00 = boneMat.a;
            tm.m01 = boneMat.b;
            tm.m04 = -boneMat.c;
            tm.m05 = -boneMat.d;
            tm.m12 = boneMat.tx;
            tm.m13 = boneMat.ty;
            node.matrix = _tempMat4;
          };
          const bones = this._armature.getBones();
          for (let l = sockets.length - 1; l >= 0; l--) {
            const sock = sockets[l];
            const boneNode = sock.target;
            if (!boneNode) continue;
            if (!boneNode.isValid) {
              socketNodes.delete(sock.path);
              sockets.splice(l, 1);
              continue;
            }
            const bone = isCached ? boneInfos[sock.boneIndex] : bones[sock.boneIndex];
            if (!bone) continue;
            matrixHandle(boneNode, bone.globalTransformMatrix);
          }
        }
      }) || _class$Q);

      class ArmatureSystem extends System {
        constructor() {
          super();
          this._armatures = new Set();
        }
        static getInstance() {
          if (!ArmatureSystem._instance) {
            ArmatureSystem._instance = new ArmatureSystem();
            director.registerSystem(ArmatureSystem.ID, ArmatureSystem._instance, System.Priority.HIGH);
          }
          return ArmatureSystem._instance;
        }
        add(armature) {
          if (!armature) return;
          if (!this._armatures.has(armature)) {
            this._armatures.add(armature);
          }
        }
        remove(armature) {
          if (!armature) return;
          if (this._armatures.has(armature)) {
            this._armatures.delete(armature);
          }
        }
        postUpdate(dt) {
          if (!this._armatures) {
            return;
          }
          this._armatures.forEach(armature => {
            armature.updateAnimation(dt);
            armature.syncAttachedNode();
          });
        }
        prepareRenderData() {
          if (!this._armatures) {
            return;
          }
          this._armatures.forEach(armature => {
            armature.markForUpdateRenderData();
          });
        }
      }
      ArmatureSystem.ID = 'ARMATURE';
      ArmatureSystem._instance = void 0;
      cclegacy.internal.ArmatureSystem = ArmatureSystem;

      var _dec$Q, _dec2$L, _class$P, _class2$L, _initializer$K, _initializer2$F, _dec3$F, _dec4$v, _dec5$t, _dec6$m, _dec7$g, _dec8$b, _dec9$9, _class4$6, _class5$5, _initializer3$x, _initializer4$u, _initializer5$p, _initializer6$k, _initializer7$g, _initializer8$e, _initializer9$c, _initializer10$b, _initializer11$b, _initializer12$a, _initializer13$7, _initializer14$6, _initializer15$5, _initializer16$5, _class6$3;
      const DefaultArmaturesEnum = {
        "default": -1
      };
      ccenum(DefaultArmaturesEnum);
      const DefaultAnimsEnum$1 = {
        "<None>": 0
      };
      ccenum(DefaultAnimsEnum$1);
      const DefaultCacheMode = {
        "REALTIME": 0
      };
      ccenum(DefaultCacheMode);
      let timeScale$1 = 1;
      const AnimationCacheMode$1 = {
        "REALTIME": 0,
        "SHARED_CACHE": 1,
        "PRIVATE_CACHE": 2
      };
      ccenum(AnimationCacheMode$1);
      const {
        ccclass: ccclass$g,
        serializable: serializable$2,
        editable: editable$3,
        type: type$4,
        help: help$1,
        menu: menu$d,
        tooltip,
        visible: visible$1,
        displayName,
        override,
        displayOrder,
        executeInEditMode: executeInEditMode$1
      } = _decorator;
      let DragonBoneSocket = (_dec$Q = ccclass$g('dragonBones.ArmatureDisplay.DragonBoneSocket'), _dec2$L = type$4(Node$1), _dec$Q(_class$P = (_class2$L = class DragonBoneSocket {
        constructor(path = '', target = null) {
          this.path = _initializer$K && _initializer$K();
          this.target = _initializer2$F && _initializer2$F();
          this.boneIndex = null;
          this.path = path;
          this.target = target;
        }
      }, (_initializer$K = applyDecoratedInitializer(_class2$L.prototype, "path", [serializable$2], function () {
        return '';
      }), _initializer2$F = applyDecoratedInitializer(_class2$L.prototype, "target", [_dec2$L, serializable$2], function () {
        return null;
      })), _class2$L)) || _class$P);
      setClassAlias(DragonBoneSocket, 'dragonBones.ArmatureDisplay.DragonBoneSocket');
      let ArmatureDisplay = (_dec3$F = ccclass$g('dragonBones.ArmatureDisplay'), _dec4$v = type$4(DragonBonesAsset), _dec5$t = type$4(DragonBonesAtlasAsset), _dec6$m = type$4(DefaultArmaturesEnum), _dec7$g = type$4(DefaultAnimsEnum$1), _dec8$b = type$4([DragonBoneSocket]), _dec9$9 = type$4(Material$1), _dec3$F(_class4$6 = (_class5$5 = (_class6$3 = class ArmatureDisplay extends UIRenderer {
        get dragonAsset() {
          return this._dragonAsset;
        }
        set dragonAsset(value) {
          this._dragonAsset = value;
          this.destroyRenderData();
          this._refresh();
        }
        get dragonAtlasAsset() {
          return this._dragonAtlasAsset;
        }
        set dragonAtlasAsset(value) {
          this._dragonAtlasAsset = value;
          this._parseDragonAtlasAsset();
          this._refresh();
        }
        get armatureName() {
          return this._armatureName;
        }
        set armatureName(name) {
          this._armatureName = name;
          const animNames = this.getAnimationNames(this._armatureName);
          if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
            {
              this.animationName = '';
            }
          }
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.remove(this._armature);
          }
          this._refresh();
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.add(this._armature);
          }
        }
        get animationName() {
          return this._animationName;
        }
        set animationName(value) {
          this._animationName = value;
        }
        get _defaultArmatureIndex() {
          return this._defaultArmatureIndexValue;
        }
        set _defaultArmatureIndex(value) {
          this._defaultArmatureIndexValue = value;
          let armatureName = '';
          if (this.dragonAsset) {
            let armaturesEnum;
            if (this.dragonAsset) {
              armaturesEnum = this.dragonAsset.getArmatureEnum();
            }
            if (!armaturesEnum) {
              errorID(7400, this.name);
              return;
            }
            armatureName = armaturesEnum[this._defaultArmatureIndex];
          }
          if (armatureName !== undefined) {
            this.armatureName = armatureName;
          } else {
            errorID(7401, this.name);
          }
          this.markForUpdateRenderData();
        }
        get _animationIndex() {
          return this._animationIndexValue;
        }
        set _animationIndex(value) {
          this._animationIndexValue = value;
          if (this._animationIndex === 0) {
            this.animationName = '';
            return;
          }
          let animsEnum;
          if (this.dragonAsset) {
            animsEnum = this.dragonAsset.getAnimsEnum(this.armatureName);
          }
          if (!animsEnum) {
            return;
          }
          const animName = animsEnum[this._animationIndex];
          if (animName !== undefined) {
            this.playAnimation(animName, this.playTimes);
          } else {
            errorID(7402, this.name);
          }
        }
        get _defaultCacheMode() {
          return this._defaultCacheModeValue;
        }
        set _defaultCacheMode(value) {
          this._defaultCacheModeValue = value;
          if (this._defaultCacheMode !== 0) {
            if (this._armature && !ArmatureCache.canCache(this._armature)) {
              this._defaultCacheMode = 0;
              warn('Animation cache mode doesn\'t support skeletal nesting');
              return;
            }
          }
          this.setAnimationCacheMode(this._defaultCacheMode);
        }
        get timeScale() {
          return this._timeScale;
        }
        set timeScale(value) {
          this._timeScale = value;
          if (this._armature && !this.isAnimationCached()) {
            this._armature.animation.timeScale = this.timeScale;
          }
        }
        get debugBones() {
          return this._debugBones;
        }
        set debugBones(value) {
          this._debugBones = value;
          this._updateDebugDraw();
        }
        get enableBatch() {
          return this._enableBatch;
        }
        set enableBatch(value) {
          if (value !== this._enableBatch) {
            this._enableBatch = value;
            this._updateBatch();
          }
        }
        get sockets() {
          return this._sockets;
        }
        set sockets(val) {
          this._verifySockets(val);
          this._sockets = val;
          this._updateSocketBindings();
          if (val.length > 0 && this._frameCache) {
            this._frameCache.enableCacheAttachedInfo();
          }
        }
        get socketNodes() {
          return this._socketNodes;
        }
        get drawList() {
          return this._drawList;
        }
        requestDrawInfo(idx) {
          if (!this._drawInfoList[idx]) {
            this._drawInfoList[idx] = new RenderDrawInfo();
          }
          return this._drawInfoList[idx];
        }
        constructor() {
          super();
          this.playTimes = _initializer3$x && _initializer3$x();
          this.premultipliedAlpha = _initializer4$u && _initializer4$u();
          this._armature = null;
          this.attachUtil = void 0;
          this._defaultArmatureIndexValue = _initializer5$p && _initializer5$p();
          this._dragonAsset = _initializer6$k && _initializer6$k();
          this._dragonAtlasAsset = _initializer7$g && _initializer7$g();
          this._armatureName = _initializer8$e && _initializer8$e();
          this._animationName = _initializer9$c && _initializer9$c();
          this._animationIndexValue = _initializer10$b && _initializer10$b();
          this._preCacheMode = -1;
          this._cacheMode = 0;
          this._defaultCacheModeValue = _initializer11$b && _initializer11$b();
          this._timeScale = _initializer12$a && _initializer12$a();
          this._playTimes = _initializer13$7 && _initializer13$7();
          this._debugBones = _initializer14$6 && _initializer14$6();
          this._enableBatch = _initializer15$5 && _initializer15$5();
          this._debugDraw = null;
          this._armatureKey = '';
          this._accTime = 0;
          this._playCount = 0;
          this._frameCache = null;
          this._curFrame = null;
          this._playing = false;
          this._armatureCache = null;
          this._eventTarget = void 0;
          this._factory = null;
          this._displayProxy = null;
          this._drawIdx = 0;
          this._drawList = new RecyclePool(() => ({
            material: null,
            texture: null,
            indexOffset: 0,
            indexCount: 0
          }), 1);
          this.maxVertexCount = 0;
          this.maxIndexCount = 0;
          this._materialCache = {};
          this._enumArmatures = Enum({});
          this._enumAnimations = Enum({});
          this._socketNodes = new Map();
          this._cachedSockets = new Map();
          this._sockets = _initializer16$5 && _initializer16$5();
          this._inited = void 0;
          this._drawInfoList = [];
          this._cacheModeEnum = void 0;
          this._eventTarget = new EventTarget();
          this._inited = false;
          this.attachUtil = new AttachUtil$1();
          this.initFactory();
          setPropertyEnumType(this, '_animationIndex', this._enumAnimations);
          setPropertyEnumType(this, '_defaultArmatureIndex', this._enumArmatures);
          this._useVertexOpacity = true;
        }
        initFactory() {
          this._factory = CCFactory$1.getInstance();
        }
        onLoad() {
          super.onLoad();
        }
        _requestDrawData(material, texture, indexOffset, indexCount) {
          const draw = this._drawList.add();
          draw.material = material;
          draw.texture = texture;
          draw.indexOffset = indexOffset;
          draw.indexCount = indexCount;
          return draw;
        }
        destroyRenderData() {
          this._drawList.reset();
          super.destroyRenderData();
        }
        getMaterialTemplate() {
          if (this.customMaterial !== null) return this.customMaterial;
          if (this.material) return this.material;
          this.updateMaterial();
          return this.material;
        }
        getMaterialForBlend(src, dst) {
          const key = `${src}/${dst}`;
          let inst = this._materialCache[key];
          if (inst) {
            return inst;
          }
          const material = this.getMaterialTemplate();
          const matInfo = {
            parent: material,
            subModelIdx: 0,
            owner: this
          };
          inst = new MaterialInstance(matInfo);
          inst.recompileShaders({
            TWO_COLORED: false,
            USE_LOCAL: false
          });
          this._materialCache[key] = inst;
          inst.overridePipelineStates({
            blendState: {
              targets: [{
                blendSrc: src,
                blendDst: dst
              }]
            }
          });
          return inst;
        }
        _updateBuiltinMaterial() {
          const material = builtinResMgr.get('default-spine-material');
          return material;
        }
        get customMaterial() {
          return this._customMaterial;
        }
        set customMaterial(val) {
          this._customMaterial = val;
          this.updateMaterial();
          this.markForUpdateRenderData();
        }
        updateMaterial() {
          let mat;
          if (this._customMaterial) mat = this._customMaterial;else mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          this._cleanMaterialCache();
        }
        _render(batcher) {
          let indicesCount = 0;
          if (this.renderData && this._drawList) {
            const rd = this.renderData;
            const chunk = rd.chunk;
            const accessor = chunk.vertexAccessor;
            const meshBuffer = rd.getMeshBuffer();
            const origin = meshBuffer.indexOffset;
            for (let i = 0; i < this._drawList.length; i++) {
              this._drawIdx = i;
              const dc = this._drawList.data[i];
              if (dc.texture) {
                batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, dc.indexCount, dc.texture, dc.material, this._enableBatch);
              }
              indicesCount += dc.indexCount;
            }
            const subIndices = rd.indices.subarray(0, indicesCount);
            accessor.appendIndices(chunk.bufferId, subIndices);
          }
        }
        __preload() {
          super.__preload();
          this._init();
        }
        _init() {
          this._cacheMode = this._defaultCacheMode;
          if (this._inited) return;
          this._inited = true;
          this._parseDragonAtlasAsset();
          this._refresh();
          const children = this.node.children;
          for (let i = 0, n = children.length; i < n; i++) {
            const child = children[i];
            if (child && child.name === 'DEBUG_DRAW_NODE') {
              child.destroy();
            }
          }
          this._updateDebugDraw();
          this._indexBoneSockets();
          this._updateSocketBindings();
        }
        getArmatureKey() {
          return this._armatureKey;
        }
        setAnimationCacheMode(cacheMode) {
          if (this._preCacheMode !== cacheMode) {
            this._cacheMode = cacheMode;
            this._buildArmature();
            if (this._armature && !this.isAnimationCached()) {
              this._factory._dragonBones.clock.add(this._armature);
            }
            this._updateSocketBindings();
            this.markForUpdateRenderData();
          }
        }
        isAnimationCached() {
          return this._cacheMode !== 0;
        }
        onEnable() {
          super.onEnable();
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.add(this._armature);
          }
          this._flushAssembler();
          ArmatureSystem.getInstance().add(this);
        }
        onDisable() {
          super.onDisable();
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.remove(this._armature);
          }
          ArmatureSystem.getInstance().remove(this);
        }
        _emitCacheCompleteEvent() {
          this._eventTarget.emit(EventObject$1.LOOP_COMPLETE);
          this._eventTarget.emit(EventObject$1.COMPLETE);
        }
        updateAnimation(dt) {
          this.markForUpdateRenderData();
          if (!this.isAnimationCached()) return;
          if (!this._frameCache) return;
          const frameCache = this._frameCache;
          if (!frameCache.isInited()) {
            return;
          }
          const frames = frameCache.frames;
          if (!this._playing) {
            if (frameCache.isInvalid()) {
              frameCache.updateToFrame();
              this._curFrame = frames[frames.length - 1];
              if (this.renderData && (this.renderData.vertexCount < frameCache.maxVertexCount || this.renderData.indexCount < frameCache.maxIndexCount)) {
                this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount;
                this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount;
                this.renderData.resize(this.maxVertexCount, this.maxIndexCount);
                if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) {
                  this.renderData.indices = new Uint16Array(this.maxIndexCount);
                }
              }
            }
            return;
          }
          const frameTime = ArmatureCache.FrameTime;
          if (this._accTime === 0 && this._playCount === 0) {
            this._eventTarget.emit(EventObject$1.START);
          }
          const globalTimeScale = timeScale$1;
          this._accTime += dt * this.timeScale * globalTimeScale;
          let frameIdx = Math.floor(this._accTime / frameTime);
          if (!frameCache.isCompleted) {
            frameCache.updateToFrame(frameIdx);
            if (this.renderData && (this.renderData.vertexCount < frameCache.maxVertexCount || this.renderData.indexCount < frameCache.maxIndexCount)) {
              this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount;
              this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount;
              this.renderData.resize(this.maxVertexCount, this.maxIndexCount);
              if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) {
                this.renderData.indices = new Uint16Array(this.maxIndexCount);
              }
            }
          }
          if (frameCache.isCompleted && frameIdx >= frames.length) {
            this._playCount++;
            if (this.playTimes > 0 && this._playCount >= this.playTimes) {
              this._curFrame = frames[frames.length - 1];
              this._accTime = 0;
              this._playing = false;
              this._playCount = 0;
              this._emitCacheCompleteEvent();
              this.attachUtil._syncAttachedNode();
              return;
            }
            this._accTime = 0;
            frameIdx = 0;
            this._emitCacheCompleteEvent();
          }
          this._curFrame = frames[frameIdx];
          this.attachUtil._syncAttachedNode();
        }
        onDestroy() {
          this._materialInstances = this._materialInstances.filter(instance => !!instance);
          this._inited = false;
          {
            if (this._cacheMode === 2) {
              this._armatureCache.dispose();
              this._armatureCache = null;
              this._armature = null;
            } else if (this._cacheMode === 1) {
              this._armatureCache = null;
              this._armature = null;
            } else if (this._armature) {
              this._armature.dispose();
              this._armature = null;
            }
          }
          this._drawList.destroy();
          super.onDestroy();
        }
        _updateDebugDraw() {
          if (this.debugBones) {
            if (!this._debugDraw) {
              const debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
              debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
              const debugDraw = debugDrawNode.addComponent(Graphics);
              debugDraw.lineWidth = 1;
              debugDraw.strokeColor = new Color$1(255, 0, 0, 255);
              this._debugDraw = debugDraw;
            }
            this._debugDraw.node.parent = this.node;
          } else if (this._debugDraw) {
            this._debugDraw.node.parent = null;
          }
          this.markForUpdateRenderData();
        }
        _updateBatch() {
          this._cleanMaterialCache();
          this.markForUpdateRenderData();
        }
        _buildArmature() {
          if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return;
          if (this._armature) {
            {
              if (this._preCacheMode === 2) {
                this._armatureCache.dispose();
              } else if (this._preCacheMode === 0) {
                this._armature.dispose();
              }
            }
            this._armatureCache = null;
            this._armature = null;
            this._displayProxy = null;
            this._frameCache = null;
            this._curFrame = null;
            this._playing = false;
            this._preCacheMode = -1;
          }
          {
            if (this._cacheMode === 1) {
              this._armatureCache = ArmatureCache.sharedCache;
            } else if (this._cacheMode === 2) {
              this._armatureCache = new ArmatureCache();
              this._armatureCache.enablePrivateMode();
            }
          }
          const atlasUUID = this.dragonAtlasAsset._uuid;
          this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID);
          if (this.isAnimationCached()) {
            this._armature = this._armatureCache.getArmatureCache(this.armatureName, this._armatureKey, atlasUUID);
            if (!this._armature) {
              this._cacheMode = 0;
            }
          }
          this._preCacheMode = this._cacheMode;
          if (this._cacheMode === 0) {
            this._displayProxy = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID);
            if (!this._displayProxy) return;
            this._displayProxy._ccNode = this.node;
            this._displayProxy._ccComponent = this;
            this._displayProxy.setEventTarget(this._eventTarget);
            this._armature = this._displayProxy._armature;
            this._armature.animation.timeScale = this.timeScale;
          }
          if (this._cacheMode !== 0 && this.debugBones) {
            warn('Debug bones is invalid in cached mode');
          }
          if (this._armature) {
            const armatureData = this._armature.armatureData;
            const aabb = armatureData.aabb;
            this.node._uiProps.uiTransformComp.setContentSize(aabb.width, aabb.height);
          }
          this.attachUtil.init(this);
          if (this.animationName) {
            this.playAnimation(this.animationName, this.playTimes);
          }
          this._flushAssembler();
        }
        querySockets() {
          if (!this._armature) {
            return [];
          }
          if (this._cachedSockets.size === 0) {
            this._indexBoneSockets();
          }
          return Array.from(this._cachedSockets.keys()).sort();
        }
        querySocketPathByName(name) {
          const ret = [];
          for (const key of this._cachedSockets.keys()) {
            if (key.endsWith(name)) {
              ret.push(key);
            }
          }
          return ret;
        }
        _parseDragonAtlasAsset() {
          if (this.dragonAtlasAsset) {
            this.dragonAtlasAsset.init(this._factory);
          }
        }
        _refresh() {
          this._buildArmature();
          this._indexBoneSockets();
          this.markForUpdateRenderData();
        }
        _updateCacheModeEnum() {
          this._cacheModeEnum = Enum({});
          if (this._armature) {
            Object.assign(this._cacheModeEnum, AnimationCacheMode$1);
          } else {
            Object.assign(this._cacheModeEnum, DefaultCacheMode);
          }
          setPropertyEnumType(this, '_defaultCacheMode', this._cacheModeEnum);
        }
        _updateAnimEnum() {
          let animEnum;
          if (this.dragonAsset) {
            animEnum = this.dragonAsset.getAnimsEnum(this.armatureName);
          } else {
            animEnum = DefaultAnimsEnum$1;
          }
          this._enumAnimations = Enum({});
          Object.assign(this._enumAnimations, animEnum || DefaultAnimsEnum$1);
          Enum.update(this._enumAnimations);
          setPropertyEnumType(this, '_animationIndex', this._enumAnimations);
        }
        _updateArmatureEnum() {
          let armatureEnum;
          if (this.dragonAsset) {
            armatureEnum = this.dragonAsset.getArmatureEnum();
          } else {
            armatureEnum = DefaultArmaturesEnum;
          }
          this._enumArmatures = Enum({});
          Object.assign(this._enumArmatures, armatureEnum || DefaultArmaturesEnum);
          Enum.update(this._enumArmatures);
          setPropertyEnumType(this, '_defaultArmatureIndex', this._enumArmatures);
        }
        _indexBoneSockets() {
          if (!this._armature) {
            return;
          }
          this._cachedSockets.clear();
          const nameToBone = this._cachedSockets;
          const cacheBoneName = (bi, bones, cache) => {
            if (cache.has(bi)) {
              return cache.get(bi);
            }
            const bone = bones[bi];
            if (!bone.parent) {
              cache.set(bi, bone.name);
              bone.path = bone.name;
              return bone.name;
            }
            const name = `${cacheBoneName(bone.parent._boneIndex, bones, cache)}/${bone.name}`;
            cache.set(bi, name);
            bone.path = name;
            return name;
          };
          const walkArmature = (prefix, armature) => {
            const bones = armature.getBones();
            const boneToName = new Map();
            for (let i = 0; i < bones.length; i++) {
              bones[i]._boneIndex = i;
            }
            for (let i = 0; i < bones.length; i++) {
              cacheBoneName(i, bones, boneToName);
            }
            for (const bone of boneToName.keys()) {
              nameToBone.set(`${prefix}${boneToName.get(bone)}`, bone);
            }
            const slots = armature.getSlots();
            for (let i = 0; i < slots.length; i++) {
              if (slots[i].childArmature) {
                walkArmature(slots[i].name, slots[i].childArmature);
              }
            }
          };
          walkArmature('', this._armature);
        }
        playAnimation(animName, playTimes) {
          this.playTimes = playTimes === undefined ? -1 : playTimes;
          this.animationName = animName;
          if (this.isAnimationCached()) {
            let cache = this._armatureCache.getAnimationCache(this._armatureKey, animName);
            if (!cache) {
              cache = this._armatureCache.initAnimationCache(this._armatureKey, animName);
            }
            if (cache) {
              this._accTime = 0;
              this._playCount = 0;
              this._frameCache = cache;
              if (this._sockets.length > 0) {
                this._frameCache.enableCacheAttachedInfo();
              }
              this._frameCache.updateToFrame(0);
              this._playing = true;
              this._curFrame = this._frameCache.frames[0];
            }
          } else if (this._armature) {
            return this._armature.animation.play(animName, this.playTimes);
          }
          this.markForUpdateRenderData();
          return null;
        }
        updateAnimationCache(animName) {
          if (!this.isAnimationCached()) return;
          this._armatureCache.updateAnimationCache(this._armatureKey, animName);
        }
        invalidAnimationCache() {
          if (!this.isAnimationCached()) return;
          this._armatureCache.invalidAnimationCache(this._armatureKey);
        }
        getArmatureNames() {
          const dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);
          return dragonBonesData && dragonBonesData.armatureNames || [];
        }
        getAnimationNames(armatureName) {
          const ret = [];
          const dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);
          if (dragonBonesData) {
            const armatureData = dragonBonesData.getArmature(armatureName);
            if (armatureData) {
              for (const animName in armatureData.animations) {
                if (armatureData.animations.hasOwnProperty(animName)) {
                  ret.push(animName);
                }
              }
            }
          }
          return ret;
        }
        on(eventType, listener, target) {
          this.addEventListener(eventType, listener, target);
        }
        off(eventType, listener, target) {
          this.removeEventListener(eventType, listener, target);
        }
        once(eventType, listener, target) {
          this._eventTarget.once(eventType, listener, target);
        }
        addEventListener(eventType, listener, target) {
          this._eventTarget.on(eventType, listener, target);
        }
        removeEventListener(eventType, listener, target) {
          this._eventTarget.off(eventType, listener, target);
        }
        buildArmature(armatureName, node) {
          return this._factory.createArmatureNode(this, armatureName, node);
        }
        armature() {
          return this._armature;
        }
        _flushAssembler() {
          const assembler = ArmatureDisplay.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._armature && this._assembler) {
            this._renderData = this._assembler.createData(this);
            if (this._renderData) {
              this.maxVertexCount = this._renderData.vertexCount;
              this.maxIndexCount = this._renderData.indexCount;
            }
            this.markForUpdateRenderData();
            this._updateColor();
          }
        }
        _updateSocketBindings() {
          if (!this._armature) return;
          this._socketNodes.clear();
          for (let i = 0, l = this._sockets.length; i < l; i++) {
            const socket = this._sockets[i];
            if (socket.path && socket.target) {
              const bone = this._cachedSockets.get(socket.path);
              if (!bone) {
                console.error(`Skeleton data does not contain path ${socket.path}`);
                continue;
              }
              socket.boneIndex = bone;
              this._socketNodes.set(socket.path, socket.target);
            }
          }
        }
        _verifySockets(sockets) {
          for (let i = 0, l = sockets.length; i < l; i++) {
            const target = sockets[i].target;
            if (target) {
              if (!target.parent || target.parent !== this.node) {
                console.error(`Target node ${target.name} is expected to be a direct child of ${this.node.name}`);
                continue;
              }
            }
          }
        }
        _cleanMaterialCache() {
          for (const val in this._materialCache) {
            this._materialCache[val].destroy();
          }
          this._materialCache = {};
        }
        createRenderEntity() {
          const renderEntity = new RenderEntity(1);
          renderEntity.setUseLocal(false);
          return renderEntity;
        }
        markForUpdateRenderData(enable = true) {
          super.markForUpdateRenderData(enable);
          if (this._debugDraw) {
            this._debugDraw.markForUpdateRenderData(enable);
          }
        }
        syncAttachedNode() {
          this.attachUtil._syncAttachedNode();
        }
      }, _class6$3.AnimationCacheMode = AnimationCacheMode$1, _class6$3), (_applyDecoratedDescriptor(_class5$5.prototype, "dragonAsset", [_dec4$v], Object.getOwnPropertyDescriptor(_class5$5.prototype, "dragonAsset"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "dragonAtlasAsset", [_dec5$t], Object.getOwnPropertyDescriptor(_class5$5.prototype, "dragonAtlasAsset"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "_defaultArmatureIndex", [_dec6$m], Object.getOwnPropertyDescriptor(_class5$5.prototype, "_defaultArmatureIndex"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "_animationIndex", [_dec7$g], Object.getOwnPropertyDescriptor(_class5$5.prototype, "_animationIndex"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "timeScale", [serializable$2], Object.getOwnPropertyDescriptor(_class5$5.prototype, "timeScale"), _class5$5.prototype), _initializer3$x = applyDecoratedInitializer(_class5$5.prototype, "playTimes", [serializable$2], function () {
        return -1;
      }), _initializer4$u = applyDecoratedInitializer(_class5$5.prototype, "premultipliedAlpha", [serializable$2], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$5.prototype, "sockets", [_dec8$b], Object.getOwnPropertyDescriptor(_class5$5.prototype, "sockets"), _class5$5.prototype), _initializer5$p = applyDecoratedInitializer(_class5$5.prototype, "_defaultArmatureIndexValue", [serializable$2], function () {
        return -1;
      }), _initializer6$k = applyDecoratedInitializer(_class5$5.prototype, "_dragonAsset", [serializable$2], function () {
        return null;
      }), _initializer7$g = applyDecoratedInitializer(_class5$5.prototype, "_dragonAtlasAsset", [serializable$2], function () {
        return null;
      }), _initializer8$e = applyDecoratedInitializer(_class5$5.prototype, "_armatureName", [serializable$2], function () {
        return '';
      }), _initializer9$c = applyDecoratedInitializer(_class5$5.prototype, "_animationName", [serializable$2], function () {
        return '';
      }), _initializer10$b = applyDecoratedInitializer(_class5$5.prototype, "_animationIndexValue", [serializable$2], function () {
        return 0;
      }), _initializer11$b = applyDecoratedInitializer(_class5$5.prototype, "_defaultCacheModeValue", [serializable$2], function () {
        return 0;
      }), _initializer12$a = applyDecoratedInitializer(_class5$5.prototype, "_timeScale", [serializable$2], function () {
        return 1;
      }), _initializer13$7 = applyDecoratedInitializer(_class5$5.prototype, "_playTimes", [serializable$2], function () {
        return -1;
      }), _initializer14$6 = applyDecoratedInitializer(_class5$5.prototype, "_debugBones", [serializable$2], function () {
        return false;
      }), _initializer15$5 = applyDecoratedInitializer(_class5$5.prototype, "_enableBatch", [serializable$2], function () {
        return false;
      }), _initializer16$5 = applyDecoratedInitializer(_class5$5.prototype, "_sockets", [serializable$2], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$5.prototype, "customMaterial", [override, _dec9$9], Object.getOwnPropertyDescriptor(_class5$5.prototype, "customMaterial"), _class5$5.prototype)), _class5$5)) || _class4$6);
      cclegacy.internal.ArmatureDisplay = ArmatureDisplay;

      const NEED_COLOR = 0x01;
      const _boneColor$1 = new Color$1(255, 0, 0, 255);
      const _slotColor$1 = new Color$1(0, 0, 255, 255);
      const _originColor$1 = new Color$1(0, 255, 0, 255);
      let _nodeR$1;
      let _nodeG$1;
      let _nodeB$1;
      let _nodeA$1;
      let _premultipliedAlpha$1;
      let _mustFlush;
      let _renderData;
      let _ibuf;
      let _vbuf;
      let _comp;
      let _vertexFloatCount = 0;
      let _vertexCount = 0;
      let _vertexOffset = 0;
      let _vertexFloatOffset = 0;
      let _indexCount = 0;
      let _indexOffset = 0;
      let _actualVCount = 0;
      let _actualICount = 0;
      let _prevDrawIndexOffset = 0;
      const LOCAL_FLOAT_PER_VERTEX = 4;
      const PER_VERTEX_SIZE = 3 + 2 + 4;
      const _c = new Float32Array(4);
      let _handleVal;
      const _tempVecPos = new Vec3(0, 0, 0);
      const _slotMat = new Mat4();
      let _currentMaterial = null;
      let _currentTexture = null;
      function _getSlotMaterial$1(tex, blendMode) {
        if (!tex) return null;
        let src;
        let dst;
        switch (blendMode) {
          case 1:
            src = _premultipliedAlpha$1 ? 1 : 2;
            dst = 1;
            break;
          case 10:
            src = 7;
            dst = 4;
            break;
          case 12:
            src = 1;
            dst = 8;
            break;
          case 0:
          default:
            src = _premultipliedAlpha$1 ? 1 : 2;
            dst = 4;
            break;
        }
        return _comp.getMaterialForBlend(src, dst);
      }
      function _handleColor(color, parentOpacity) {
        const _a = color.a * parentOpacity * _nodeA$1;
        const _multiply = _premultipliedAlpha$1 ? _a / 255.0 : 1.0;
        const _r = color.r * _nodeR$1 * _multiply / 255.0;
        const _g = color.g * _nodeG$1 * _multiply / 255.0;
        const _b = color.b * _nodeB$1 * _multiply / 255.0;
        _c[0] = _r;
        _c[1] = _g;
        _c[2] = _b;
        _c[3] = _premultipliedAlpha$1 ? 1.0 : _a / 255.0;
      }
      let _accessor$2 = null;
      const simple$2 = {
        accessor: _accessor$2,
        vCount: 32767,
        ensureAccessor() {
          if (!_accessor$2) {
            const device = director.root.device;
            const batcher = director.root.batcher2D;
            const attributes = vfmtPosUvColor;
            this.accessor = _accessor$2 = new StaticVBAccessor(device, attributes, this.vCount);
            batcher.registerBufferAccessor(Number.parseInt('DRAGONBONES', 36), _accessor$2);
          }
          return this.accessor;
        },
        createData(comp) {
          let rd = comp.renderData;
          if (!rd) {
            this.ensureAccessor();
            const slots = comp._armature._slots;
            let vCount = 0;
            let iCount = 0;
            for (let i = 0; i < slots.length; ++i) {
              const slot = slots[i];
              const remainder = slot._localVertices.length % 4;
              if (remainder === 0) {
                vCount += slot._localVertices.length / LOCAL_FLOAT_PER_VERTEX;
              } else {
                vCount += (slot._localVertices.length - remainder) / LOCAL_FLOAT_PER_VERTEX + 1;
              }
              iCount += slot._indices.length;
            }
            rd = RenderData.add(vfmtPosUvColor, this.accessor);
            rd.resize(vCount, iCount);
            if (!rd.indices || iCount !== rd.indices.length) {
              rd.indices = new Uint16Array(iCount);
            }
          }
          return rd;
        },
        updateRenderData(comp, batcher) {
          _comp = comp;
          const armature = comp._armature;
          if (armature) {
            updateComponentRenderData$1(comp);
          }
        },
        updateColor(comp) {
          if (!comp) return;
          _comp = comp;
          _comp.markForUpdateRenderData();
        }
      };
      function realTimeTraverse$1(armature, parentOpacity, worldMat) {
        const rd = _renderData;
        _vbuf = rd.chunk.vb;
        _ibuf = rd.indices;
        const slots = armature._slots;
        let material;
        let vertices;
        let indices;
        let slotColor;
        let slot;
        let cumulatedCount = 0;
        for (let i = 0, l = slots.length; i < l; i++) {
          slot = slots[i];
          slotColor = slot._color;
          if (!slot._visible || !slot._displayData) continue;
          if (worldMat) {
            Mat4.multiply(slot._worldMatrix, worldMat, slot._matrix);
          } else {
            Mat4.copy(slot._worldMatrix, slot._matrix);
          }
          if (slot.childArmature) {
            realTimeTraverse$1(slot.childArmature, slotColor.a / 255, slot._worldMatrix);
            continue;
          }
          material = _getSlotMaterial$1(slot.getTexture(), slot._blendMode);
          if (!material) {
            continue;
          }
          if (!_currentMaterial) _currentMaterial = material;
          const texture = slot.getTexture();
          if (_mustFlush || material.hash !== _currentMaterial.hash || texture && _currentTexture !== texture) {
            _mustFlush = false;
            const cumulatedCount = _indexOffset - _prevDrawIndexOffset;
            if (cumulatedCount > 0) {
              _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
              _prevDrawIndexOffset = _indexOffset;
            }
            _currentTexture = texture;
            _currentMaterial = material;
          }
          _handleColor(slotColor, parentOpacity);
          _slotMat.set(slot._worldMatrix);
          vertices = slot._localVertices;
          _vertexCount = vertices.length / LOCAL_FLOAT_PER_VERTEX;
          _vertexFloatCount = _vertexCount * PER_VERTEX_SIZE;
          indices = slot._indices;
          _indexCount = indices.length;
          let isResize = false;
          if (_vertexOffset + _vertexCount > _actualVCount) {
            _actualVCount = _vertexOffset + _vertexCount;
            isResize = true;
          }
          if (_indexOffset + _indexCount > _actualICount) {
            _actualICount = _indexOffset + _indexCount;
            isResize = true;
          }
          if (isResize) {
            const oldIndices = _ibuf;
            const oldChunkOffset = rd.chunk.vertexOffset;
            rd.resizeAndCopy(_actualVCount, _actualICount > rd.indexCount ? _actualICount : rd.indexCount);
            _vbuf = rd.chunk.vb;
            if (_actualICount > _ibuf.length) {
              _ibuf = rd.indices = new Uint16Array(_actualICount);
            }
            const correction = rd.chunk.vertexOffset - oldChunkOffset;
            for (let i = 0; i < _indexOffset; ++i) {
              _ibuf[i] = oldIndices[i] + correction;
            }
          }
          for (let vi = 0, vl = vertices.length, v = _vertexFloatOffset; vi < vl; v += PER_VERTEX_SIZE) {
            _tempVecPos.x = vertices[vi++];
            _tempVecPos.y = vertices[vi++];
            _tempVecPos.z = 0;
            _tempVecPos.transformMat4(_slotMat);
            _vbuf[v] = _tempVecPos.x;
            _vbuf[v + 1] = _tempVecPos.y;
            _vbuf[v + 2] = _tempVecPos.z;
            _vbuf[v + 3] = vertices[vi++];
            _vbuf[v + 4] = vertices[vi++];
            _vbuf.set(_c, v + 5);
          }
          const chunkOffset = rd.chunk.vertexOffset;
          for (let i = 0, il = indices.length, ii = _indexOffset; i < il; i++, ii++) {
            _ibuf[ii] = _vertexOffset + indices[i] + chunkOffset;
          }
          _vertexFloatOffset += _vertexFloatCount;
          _vertexOffset += _vertexCount;
          _indexOffset += _indexCount;
          _vertexCount = 0;
          _indexCount = 0;
        }
        cumulatedCount = _indexOffset - _prevDrawIndexOffset;
        if (_currentTexture && cumulatedCount > 0) {
          _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
          _prevDrawIndexOffset = _indexOffset;
        }
        if (_comp.maxIndexCount < _actualICount) {
          _comp.maxIndexCount = _actualICount;
        }
        if (_comp.maxVertexCount < _actualVCount) {
          _comp.maxVertexCount = _actualVCount;
        }
      }
      function cacheTraverse$1(frame, parentMat) {
        if (!frame) return;
        const segments = frame.segments;
        if (segments.length === 0) return;
        let material = null;
        const vertices = frame.vertices;
        const indices = frame.indices;
        let chunkOffset = 0;
        let frameVFOffset = 0;
        let frameIndexOffset = 0;
        let segVFCount = 0;
        let colorOffset = 0;
        const colors = frame.colors;
        let nowColor = colors[colorOffset++];
        let maxVFOffset = nowColor.vfOffset;
        _handleColor(nowColor, 1.0);
        const rd = _renderData;
        const vbuf = rd.chunk.vb;
        const ibuf = rd.indices;
        for (let i = 0, n = segments.length; i < n; i++) {
          const segInfo = segments[i];
          material = _getSlotMaterial$1(segInfo.tex, segInfo.blendMode);
          if (!material) continue;
          if (!_currentMaterial) _currentMaterial = material;
          if (_mustFlush || material.hash !== _currentMaterial.hash || segInfo.tex && segInfo.tex !== _currentTexture) {
            _mustFlush = false;
            const cumulatedCount = _indexOffset - _prevDrawIndexOffset;
            if (cumulatedCount > 0) {
              _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
              _prevDrawIndexOffset = _indexOffset;
            }
            _currentMaterial = material;
            _currentTexture = segInfo.tex;
          }
          _vertexCount = segInfo.vertexCount;
          _indexCount = segInfo.indexCount;
          chunkOffset = rd.chunk.vertexOffset;
          for (let ii = _indexOffset, il = _indexOffset + _indexCount; ii < il; ii++) {
            ibuf[ii] = chunkOffset + _vertexOffset + indices[frameIndexOffset++];
          }
          segVFCount = segInfo.vfCount;
          const subArray = vertices.subarray(frameVFOffset, segVFCount);
          vbuf.set(subArray, frameVFOffset);
          let offset = 0;
          if (parentMat) {
            for (let ii = 0, il = _vertexCount; ii < il; ii++) {
              _tempVecPos.x = vbuf[offset];
              _tempVecPos.y = vbuf[offset + 1];
              _tempVecPos.z = 0;
              _tempVecPos.transformMat4(parentMat);
              vbuf[offset] = _tempVecPos.x;
              vbuf[offset + 1] = _tempVecPos.y;
              vbuf[offset + 2] = _tempVecPos.z;
              offset += PER_VERTEX_SIZE;
            }
          }
          if (_handleVal & NEED_COLOR) {
            let frameColorOffset = frameVFOffset / 9 * 5;
            for (let ii = frameVFOffset, iEnd = frameVFOffset + segVFCount; ii < iEnd; ii += PER_VERTEX_SIZE, frameColorOffset += 5) {
              if (frameColorOffset >= maxVFOffset) {
                nowColor = colors[colorOffset++];
                _handleColor(nowColor, 1.0);
                maxVFOffset = nowColor.vfOffset;
              }
              vbuf.set(_c, ii + 5);
            }
          }
          frameVFOffset += segVFCount;
          _vertexOffset += _vertexCount;
          _indexOffset += _indexCount;
          _vertexCount = 0;
          _indexCount = 0;
        }
        const cumulatedCount = _indexOffset - _prevDrawIndexOffset;
        if (_currentTexture && cumulatedCount > 0) {
          _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
        }
      }
      function updateComponentRenderData$1(comp, batcher) {
        const armature = comp._armature;
        if (!armature || comp.renderData === null) return;
        _mustFlush = true;
        _premultipliedAlpha$1 = comp.premultipliedAlpha;
        comp.drawList.reset();
        _comp = comp;
        comp.node;
        _renderData = comp.renderData;
        _comp = comp;
        _handleVal = 0;
        _currentMaterial = null;
        const nodeColor = comp.color;
        _nodeR$1 = nodeColor.r / 255;
        _nodeG$1 = nodeColor.g / 255;
        _nodeB$1 = nodeColor.b / 255;
        _nodeA$1 = comp.node._uiProps.opacity;
        if (Color$1.toUint32(nodeColor) !== 0xffffffff) {
          _handleVal |= NEED_COLOR;
        }
        const worldMat = comp.node.getWorldMatrix();
        _vertexFloatCount = 0;
        _vertexOffset = 0;
        _vertexFloatOffset = 0;
        _indexCount = 0;
        _indexOffset = 0;
        _prevDrawIndexOffset = 0;
        _actualVCount = _comp.maxVertexCount;
        _actualICount = _comp.maxIndexCount;
        if (comp.isAnimationCached()) {
          cacheTraverse$1(comp._curFrame, worldMat);
        } else {
          realTimeTraverse$1(armature, 1.0, worldMat);
          const graphics = comp._debugDraw;
          if (comp.debugBones && graphics) {
            graphics.clear();
            graphics.lineWidth = 5;
            graphics.strokeColor = _boneColor$1;
            graphics.fillColor = _slotColor$1;
            const bones = armature.getBones();
            for (let i = 0, l = bones.length; i < l; i++) {
              const bone = bones[i];
              const boneLength = Math.max(bone.boneData.length, 5);
              const startX = bone.globalTransformMatrix.tx;
              const startY = bone.globalTransformMatrix.ty;
              const endX = startX + bone.globalTransformMatrix.a * boneLength;
              const endY = startY + bone.globalTransformMatrix.b * boneLength;
              graphics.moveTo(startX, startY);
              graphics.lineTo(endX, endY);
              graphics.stroke();
              graphics.circle(startX, startY, Math.PI * 2);
              graphics.fill();
              if (i === 0) {
                graphics.fillColor = _originColor$1;
              }
            }
          }
        }
        _accessor$2.getMeshBuffer(_renderData.chunk.bufferId).setDirty();
        _comp = undefined;
      }
      cclegacy.internal.DragonBonesAssembler = simple$2;

      const simpleDragonBoneAssembler = {
        getAssembler() {
          return simple$2;
        }
      };
      ArmatureDisplay.Assembler = simpleDragonBoneAssembler;

      let ExtensionType;
      (function (ExtensionType) {
        ExtensionType[ExtensionType["FFD"] = 0] = "FFD";
        ExtensionType[ExtensionType["AdjustColor"] = 10] = "AdjustColor";
        ExtensionType[ExtensionType["BevelFilter"] = 11] = "BevelFilter";
        ExtensionType[ExtensionType["BlurFilter"] = 12] = "BlurFilter";
        ExtensionType[ExtensionType["DropShadowFilter"] = 13] = "DropShadowFilter";
        ExtensionType[ExtensionType["GlowFilter"] = 14] = "GlowFilter";
        ExtensionType[ExtensionType["GradientBevelFilter"] = 15] = "GradientBevelFilter";
        ExtensionType[ExtensionType["GradientGlowFilter"] = 16] = "GradientGlowFilter";
      })(ExtensionType || (ExtensionType = {}));
      let DragonBonesEventType;
      (function (DragonBonesEventType) {
        DragonBonesEventType[DragonBonesEventType["Frame"] = 0] = "Frame";
        DragonBonesEventType[DragonBonesEventType["Sound"] = 1] = "Sound";
      })(DragonBonesEventType || (DragonBonesEventType = {}));
      const EventType = DragonBonesEventType;
      let AnimationFadeOutMode;
      (function (AnimationFadeOutMode) {
        AnimationFadeOutMode[AnimationFadeOutMode["None"] = 0] = "None";
        AnimationFadeOutMode[AnimationFadeOutMode["SameLayer"] = 1] = "SameLayer";
        AnimationFadeOutMode[AnimationFadeOutMode["SameGroup"] = 2] = "SameGroup";
        AnimationFadeOutMode[AnimationFadeOutMode["SameLayerAndGroup"] = 3] = "SameLayerAndGroup";
        AnimationFadeOutMode[AnimationFadeOutMode["All"] = 4] = "All";
      })(AnimationFadeOutMode || (AnimationFadeOutMode = {}));
      const dragonBones = globalThis.dragonBones;
      const Slot = dragonBones.Slot;
      const Matrix = dragonBones.Matrix;
      const BaseObject = dragonBones.BaseObject;
      const BoundingBoxData = dragonBones.BoundingBoxData;
      const PolygonBoundingBoxData = dragonBones.PolygonBoundingBoxData;
      const Transform = dragonBones.Transform;
      const Animation = dragonBones.Animation;
      const TextureData = dragonBones.TextureData;
      const CCTextureData = dragonBones.CCTextureData;
      const BaseFactory = dragonBones.BaseFactory;
      const CCFactory = dragonBones.CCFactory;
      const WorldClock = dragonBones.WorldClock;
      const TextureAtlasData = dragonBones.TextureAtlasData;
      const CCArmatureDisplay = dragonBones.CCArmatureDisplay;
      const AnimationState = dragonBones.AnimationState;
      const BoneData = dragonBones.BoneData;
      const EllipseBoundingBoxData = dragonBones.EllipseBoundingBoxData;
      const ArmatureData = dragonBones.ArmatureData;
      const CCTextureAtlasData = dragonBones.CCTextureAtlasData;
      const TransformObject = dragonBones.TransformObject;
      const CCSlot = dragonBones.CCSlot;
      const Armature = dragonBones.Armature;
      const Bone = dragonBones.Bone;
      const RectangleBoundingBoxData = dragonBones.RectangleBoundingBoxData;
      const ArmatureCacheMgr = dragonBones.ArmatureCacheMgr;
      const SkinData = dragonBones.SkinData;
      const EventObject = dragonBones.EventObject;
      const SlotData = dragonBones.SlotData;
      const DragonBonesData = dragonBones.DragonBonesData;
      const AnimationData = dragonBones.AnimationData;
      const CCArmatureCacheDisplay = dragonBones.CCArmatureCacheDisplay;

      var index$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        Animation: Animation,
        AnimationCacheMode: AnimationCacheMode$1,
        AnimationData: AnimationData,
        get AnimationFadeOutMode () { return AnimationFadeOutMode; },
        AnimationState: AnimationState,
        Armature: Armature,
        ArmatureCacheMgr: ArmatureCacheMgr,
        ArmatureData: ArmatureData,
        ArmatureDisplay: ArmatureDisplay,
        AttachUtil: AttachUtil$1,
        BaseFactory: BaseFactory,
        BaseObject: BaseObject,
        Bone: Bone,
        BoneData: BoneData,
        BoundingBoxData: BoundingBoxData,
        CCArmatureCacheDisplay: CCArmatureCacheDisplay,
        CCArmatureDisplay: CCArmatureDisplay,
        CCFactory: CCFactory,
        CCSlot: CCSlot,
        CCTextureAtlasData: CCTextureAtlasData,
        CCTextureData: CCTextureData,
        DragonBoneSocket: DragonBoneSocket,
        DragonBonesAsset: DragonBonesAsset,
        DragonBonesAtlasAsset: DragonBonesAtlasAsset,
        DragonBonesData: DragonBonesData,
        get DragonBonesEventType () { return DragonBonesEventType; },
        EllipseBoundingBoxData: EllipseBoundingBoxData,
        EventObject: EventObject,
        EventType: EventType,
        get ExtensionType () { return ExtensionType; },
        Matrix: Matrix,
        PolygonBoundingBoxData: PolygonBoundingBoxData,
        RectangleBoundingBoxData: RectangleBoundingBoxData,
        SkinData: SkinData,
        Slot: Slot,
        SlotData: SlotData,
        TextureAtlasData: TextureAtlasData,
        TextureData: TextureData,
        Transform: Transform,
        TransformObject: TransformObject,
        WorldClock: WorldClock,
        simpleDragonBoneAssembler: simpleDragonBoneAssembler,
        timeScale: timeScale$1
      });
      exports("dragonBones", index$1);

      function lineLine(a1, a2, b1, b2) {
        const ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
        const ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
        const u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
        if (u_b !== 0) {
          const ua = ua_t / u_b;
          const ub = ub_t / u_b;
          if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
            return true;
          }
        }
        return false;
      }
      const tempR1 = new Vec2();
      const tempR2 = new Vec2();
      const tempR3 = new Vec2();
      const tempR4 = new Vec2();
      function lineRect(a1, a2, b) {
        const r0 = tempR1.set(b.x, b.y);
        const r1 = tempR2.set(b.x, b.yMax);
        const r2 = tempR3.set(b.xMax, b.yMax);
        const r3 = tempR4.set(b.xMax, b.y);
        if (lineLine(a1, a2, r0, r1)) return true;
        if (lineLine(a1, a2, r1, r2)) return true;
        if (lineLine(a1, a2, r2, r3)) return true;
        if (lineLine(a1, a2, r3, r0)) return true;
        return false;
      }
      function linePolygon(a1, a2, b) {
        const length = b.length;
        for (let i = 0; i < length; ++i) {
          const b1 = b[i];
          const b2 = b[(i + 1) % length];
          if (lineLine(a1, a2, b1, b2)) return true;
        }
        return false;
      }
      function rectRect(a, b) {
        const a_min_x = a.x;
        const a_min_y = a.y;
        const a_max_x = a.x + a.width;
        const a_max_y = a.y + a.height;
        const b_min_x = b.x;
        const b_min_y = b.y;
        const b_max_x = b.x + b.width;
        const b_max_y = b.y + b.height;
        return a_min_x <= b_max_x && a_max_x >= b_min_x && a_min_y <= b_max_y && a_max_y >= b_min_y;
      }
      function rectPolygon(a, b) {
        const r0 = tempR1.set(a.x, a.y);
        const r1 = tempR2.set(a.x, a.yMax);
        const r2 = tempR3.set(a.xMax, a.yMax);
        const r3 = tempR4.set(a.xMax, a.y);
        if (linePolygon(r0, r1, b)) return true;
        if (linePolygon(r1, r2, b)) return true;
        if (linePolygon(r2, r3, b)) return true;
        if (linePolygon(r3, r0, b)) return true;
        for (let i = 0, l = b.length; i < l; ++i) {
          if (a.contains(b[i])) return true;
        }
        if (pointInPolygon(r0, b)) return true;
        if (pointInPolygon(r1, b)) return true;
        if (pointInPolygon(r2, b)) return true;
        if (pointInPolygon(r3, b)) return true;
        return false;
      }
      function polygonPolygon(a, b) {
        let i;
        let l;
        for (i = 0, l = a.length; i < l; ++i) {
          const a1 = a[i];
          const a2 = a[(i + 1) % l];
          if (linePolygon(a1, a2, b)) return true;
        }
        for (i = 0, l = b.length; i < l; ++i) {
          if (pointInPolygon(b[i], a)) return true;
        }
        for (i = 0, l = a.length; i < l; ++i) {
          if (pointInPolygon(a[i], b)) return true;
        }
        return false;
      }
      function circleCircle(c1p, c1r, c2p, c2r) {
        const distance = Vec2.distance(c1p, c2p);
        return distance < c1r + c2r;
      }
      function polygonCircle(polygon, cp, cr) {
        const position = cp;
        if (pointInPolygon(position, polygon)) {
          return true;
        }
        for (let i = 0, l = polygon.length; i < l; i++) {
          const start = i === 0 ? polygon[polygon.length - 1] : polygon[i - 1];
          const end = polygon[i];
          if (pointLineDistance(position, start, end, true) < cr) {
            return true;
          }
        }
        return false;
      }
      function rectCircle(rect, cp, cr) {
        const cx = cp.x;
        const cy = cp.y;
        const rx = rect.x;
        const ry = rect.y;
        const rw = rect.width;
        const rh = rect.height;
        let testX = cx;
        let testY = cy;
        if (cx < rx) testX = rx;else if (cx > rx + rw) testX = rx + rw;
        if (cy < ry) testY = ry;else if (cy > ry + rh) testY = ry + rh;
        const distX = cx - testX;
        const distY = cy - testY;
        const distance = Math.sqrt(distX * distX + distY * distY);
        if (distance <= cr) {
          return true;
        }
        return false;
      }
      function pointInPolygon(point, polygon) {
        let inside = false;
        const x = point.x;
        const y = point.y;
        const length = polygon.length;
        for (let i = 0, j = length - 1; i < length; j = i++) {
          const xi = polygon[i].x;
          const yi = polygon[i].y;
          const xj = polygon[j].x;
          const yj = polygon[j].y;
          const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
          if (intersect) inside = !inside;
        }
        return inside;
      }
      function pointLineDistance(point, start, end, isSegment) {
        let dx = end.x - start.x;
        let dy = end.y - start.y;
        const d = dx * dx + dy * dy;
        const t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d;
        let p;
        if (!isSegment) {
          p = tempR1.set(start.x + t * dx, start.y + t * dy);
        } else if (d) {
          if (t < 0) p = start;else if (t > 1) p = end;else p = tempR1.set(start.x + t * dx, start.y + t * dy);
        } else {
          p = start;
        }
        dx = point.x - p.x;
        dy = point.y - p.y;
        return Math.sqrt(dx * dx + dy * dy);
      }
      class Intersection2D {} exports("Intersection2D", Intersection2D);
      Intersection2D.lineLine = lineLine;
      Intersection2D.lineRect = lineRect;
      Intersection2D.linePolygon = linePolygon;
      Intersection2D.rectRect = rectRect;
      Intersection2D.rectPolygon = rectPolygon;
      Intersection2D.rectCircle = rectCircle;
      Intersection2D.polygonPolygon = polygonPolygon;
      Intersection2D.circleCircle = circleCircle;
      Intersection2D.polygonCircle = polygonCircle;
      Intersection2D.pointInPolygon = pointInPolygon;
      Intersection2D.pointLineDistance = pointLineDistance;

      var _dec$P, _dec2$K, _class$O, _class2$K, _initializer$J, _initializer2$E, _dec3$E, _dec4$u, _class4$5, _initializer3$w, _initializer4$t, _initializer5$o;
      function createDefaultPipeline() {
        const rppl = new ForwardPipeline();
        if (!window.oh) {
          rppl.initialize({
            flows: []
          });
        }
        return rppl;
      }
      const ForwardPipeline = exports("ForwardPipeline", nr.ForwardPipeline);
      const ForwardFlow = exports("ForwardFlow", nr.ForwardFlow);
      const ShadowFlow = exports("ShadowFlow", nr.ShadowFlow);
      const ForwardStage = exports("ForwardStage", nr.ForwardStage);
      const ShadowStage = exports("ShadowStage", nr.ShadowStage);
      const DeferredPipeline = exports("DeferredPipeline", nr.DeferredPipeline);
      const MainFlow = exports("MainFlow", nr.MainFlow);
      const LightingStage = exports("LightingStage", nr.LightingStage);
      const PostProcessStage = exports("PostProcessStage", nr.PostProcessStage);
      const GbufferStage = exports("GbufferStage", nr.GbufferStage);
      const BloomStage = exports("BloomStage", nr.BloomStage);
      const ReflectionProbeFlow = exports("ReflectionProbeFlow", nr.ReflectionProbeFlow);
      const ReflectionProbeStage = exports("ReflectionProbeStage", nr.ReflectionProbeStage);
      const RenderPipeline = exports("RenderPipeline", nr.RenderPipeline);
      const RenderFlow = exports("RenderFlow", nr.RenderFlow);
      const RenderStage = exports("RenderStage", nr.RenderStage);
      legacyCC.RenderFlow = RenderFlow;
      legacyCC.RenderStage = RenderStage;
      legacyCC.RenderPipeline = RenderPipeline;
      const forwardPipelineProto = ForwardPipeline.prototype;
      forwardPipelineProto._ctor = function () {
        this._tag = 0;
        this._flows = [];
      };
      forwardPipelineProto.init = function () {
        for (let i = 0; i < this._flows.length; i++) {
          this._flows[i].init(this);
        }
        const info = {
          tag: this._tag,
          flows: this._flows
        };
        this.initialize(info);
      };
      const oldForwardOnLoaded = forwardPipelineProto.onLoaded;
      forwardPipelineProto.onLoaded = function () {
        if (oldForwardOnLoaded) oldForwardOnLoaded.call(this);
        for (let i = 0; i < this._flows.length; i++) {
          this._flows[i].init(this);
        }
        const info = {
          tag: this._tag,
          flows: this._flows
        };
        this.initialize(info);
      };
      const forwardFlowProto = ForwardFlow.prototype;
      forwardFlowProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this._stages = [];
      };
      forwardFlowProto.init = function (pipeline) {
        for (let i = 0; i < this._stages.length; i++) {
          this._stages[i].init(pipeline);
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          stages: this._stages
        };
        this.initialize(info);
      };
      const shadowFlowProto = ShadowFlow.prototype;
      shadowFlowProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this._stages = [];
      };
      shadowFlowProto.init = function (pipeline) {
        for (let i = 0; i < this._stages.length; i++) {
          this._stages[i].init(pipeline);
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          stages: this._stages
        };
        this.initialize(info);
      };
      const forwardStageProto = ForwardStage.prototype;
      forwardStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
      };
      forwardStageProto.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      const shadowStageProto = ShadowStage.prototype;
      shadowStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
      };
      shadowStageProto.init = function (pipeline) {
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: []
        };
        this.initialize(info);
      };
      const deferredPipelineProto = DeferredPipeline.prototype;
      deferredPipelineProto._ctor = function () {
        this._tag = 0;
        this._flows = [];
        this.renderTextures = [];
        this.materials = [];
      };
      const oldDeferredOnLoaded = deferredPipelineProto.onLoaded;
      deferredPipelineProto.onLoaded = function () {
        if (oldDeferredOnLoaded) oldDeferredOnLoaded.call(this);
        for (let i = 0; i < this._flows.length; i++) {
          this._flows[i].init(this);
        }
        let info = {
          tag: this._tag,
          flows: this._flows
        };
        this.initialize(info);
      };
      const mainFlowProto = MainFlow.prototype;
      mainFlowProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this._stages = [];
      };
      mainFlowProto.init = function (pipeline) {
        for (let i = 0; i < this._stages.length; i++) {
          this._stages[i].init(pipeline);
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          stages: this._stages
        };
        this.initialize(info);
      };
      const gbufferStageProto = GbufferStage.prototype;
      gbufferStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
      };
      gbufferStageProto.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      const lightingStageProto = LightingStage.prototype;
      lightingStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
        this._deferredMaterial = null;
      };
      lightingStageProto.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        pipeline.pipelineSceneData.deferredLightingMaterial = this._deferredMaterial;
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      const bloomStageProto = BloomStage.prototype;
      bloomStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
        this._bloomMaterial = null;
      };
      bloomStageProto.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        pipeline.pipelineSceneData.bloomMaterial = this._bloomMaterial;
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      const postProcessStageProto = PostProcessStage.prototype;
      postProcessStageProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
        this._postProcessMaterial = null;
      };
      postProcessStageProto.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        pipeline.pipelineSceneData.postProcessMaterial = this._postProcessMaterial;
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      const reflectionProbeFlowProto = ReflectionProbeFlow.prototype;
      reflectionProbeFlowProto._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this._stages = [];
      };
      reflectionProbeFlowProto.init = function (pipeline) {
        for (let i = 0; i < this._stages.length; i++) {
          this._stages[i].init(pipeline);
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          stages: this._stages
        };
        this.initialize(info);
      };
      const reflectionProbeStage = ReflectionProbeStage.prototype;
      reflectionProbeStage._ctor = function () {
        this._name = 0;
        this._priority = 0;
        this._tag = 0;
        this.renderQueues = [];
      };
      reflectionProbeStage.init = function (pipeline) {
        const queues = [];
        for (let i = 0; i < this.renderQueues.length; i++) {
          queues.push(this.renderQueues[i].init());
        }
        const info = {
          name: this._name,
          priority: this._priority,
          tag: this._tag,
          renderQueues: queues
        };
        this.initialize(info);
      };
      let RenderTextureConfig = (_dec$P = ccclass$H('RenderTextureConfig'), _dec2$K = type$a(RenderTexture), _dec$P(_class$O = (_class2$K = class RenderTextureConfig {
        constructor() {
          this.name = _initializer$J && _initializer$J();
          this.texture = _initializer2$E && _initializer2$E();
        }
      }, (_initializer$J = applyDecoratedInitializer(_class2$K.prototype, "name", [serializable$l], function () {
        return '';
      }), _initializer2$E = applyDecoratedInitializer(_class2$K.prototype, "texture", [_dec2$K], function () {
        return null;
      })), _class2$K)) || _class$O);
      let RenderQueueSortMode; exports("RenderQueueSortMode", RenderQueueSortMode);
      (function (RenderQueueSortMode) {
        RenderQueueSortMode[RenderQueueSortMode["FRONT_TO_BACK"] = 0] = "FRONT_TO_BACK";
        RenderQueueSortMode[RenderQueueSortMode["BACK_TO_FRONT"] = 1] = "BACK_TO_FRONT";
      })(RenderQueueSortMode || (exports("RenderQueueSortMode", RenderQueueSortMode = {})));
      ccenum(RenderQueueSortMode);
      let RenderQueueDesc = exports("RenderQueueDesc", (_dec3$E = type$a(RenderQueueSortMode), _dec4$u = type$a([CCString]), (_class4$5 = class RenderQueueDesc {
        constructor() {
          this.isTransparent = _initializer3$w && _initializer3$w();
          this.sortMode = _initializer4$t && _initializer4$t();
          this.stages = _initializer5$o && _initializer5$o();
          this.stages = [];
        }
        init() {
          return new nr.RenderQueueDesc(this.isTransparent, this.sortMode, this.stages);
        }
      }, (_initializer3$w = applyDecoratedInitializer(_class4$5.prototype, "isTransparent", [serializable$l], function () {
        return false;
      }), _initializer4$t = applyDecoratedInitializer(_class4$5.prototype, "sortMode", [_dec3$E], function () {
        return 0;
      }), _initializer5$o = applyDecoratedInitializer(_class4$5.prototype, "stages", [_dec4$u], function () {
        return [];
      })), _class4$5)));
      function proxyArrayAttributeImpl(proto, attr) {
        const proxyTarget = `_${attr}_target`;
        let arrayProxy = (self, targetArrayAttr) => {
          return new Proxy(self[targetArrayAttr], {
            get(targetArray, prop, receiver) {
              return Reflect.get(targetArray, prop, receiver);
            },
            set(targetArray, prop, receiver) {
              const ret = Reflect.set(targetArray, prop, receiver);
              self[targetArrayAttr] = targetArray;
              return ret;
            }
          });
        };
        Object.defineProperty(proto, attr, {
          configurable: true,
          enumerable: true,
          get: function () {
            this[proxyTarget] || (this[proxyTarget] = []);
            return arrayProxy(this, proxyTarget);
          },
          set: function (v) {
            this[proxyTarget] = v;
          }
        });
      }
      let proxyArrayAttribute = proxyArrayAttributeImpl;
      {
        proxyArrayAttribute(RenderFlow.prototype, '_stages');
        proxyArrayAttribute(RenderPipeline.prototype, '_flows');
      }
      const Material = jsb.Material;
      patch_GbufferStage({
        GbufferStage,
        RenderQueueDesc
      });
      patch_LightingStage({
        LightingStage,
        RenderQueueDesc,
        Material
      });
      patch_BloomStage({
        BloomStage,
        Material
      });
      patch_PostProcessStage({
        PostProcessStage,
        Material,
        RenderQueueDesc
      });
      patch_ForwardStage({
        ForwardStage,
        RenderQueueDesc
      });
      patch_ShadowStage({
        ShadowStage
      });
      patch_ReflectionProbeStage({
        ReflectionProbeStage
      });
      patch_MainFlow({
        MainFlow
      });
      patch_ForwardFlow({
        ForwardFlow
      });
      patch_ShadowFlow({
        ShadowFlow
      });
      patch_ReflectionProbeFlow({
        ReflectionProbeFlow
      });
      patch_ForwardPipeline({
        ForwardPipeline,
        RenderTextureConfig
      });
      patch_DeferredPipeline({
        DeferredPipeline,
        RenderTextureConfig
      });
      patch_RenderQueueDesc({
        RenderQueueDesc,
        RenderQueueSortMode,
        CCString
      });
      patch_RenderStage({
        RenderStage
      });
      patch_RenderFlow({
        RenderFlow,
        RenderStage
      });
      patch_cc_RenderPipeline({
        RenderPipeline,
        RenderFlow
      });

      var legacy_rendering = /*#__PURE__*/Object.freeze({
        __proto__: null,
        BloomStage: BloomStage,
        DeferredPipeline: DeferredPipeline,
        ForwardFlow: ForwardFlow,
        ForwardPipeline: ForwardPipeline,
        ForwardStage: ForwardStage,
        GbufferStage: GbufferStage,
        LightingStage: LightingStage,
        MainFlow: MainFlow,
        PostProcessStage: PostProcessStage,
        ReflectionProbeFlow: ReflectionProbeFlow,
        ReflectionProbeStage: ReflectionProbeStage,
        RenderFlow: RenderFlow,
        RenderPipeline: RenderPipeline,
        RenderQueueDesc: RenderQueueDesc,
        get RenderQueueSortMode () { return RenderQueueSortMode; },
        RenderStage: RenderStage,
        ShadowFlow: ShadowFlow,
        ShadowStage: ShadowStage,
        createDefaultPipeline: createDefaultPipeline
      });

      legacyCC.legacy_rendering = legacy_rendering;

      const PlaceMethod = exports("PlaceMethod", Enum({
        UNIFORM: 0,
        ADAPTIVE: 1
      }));
      class AutoPlacement {
        static generate(info) {
          switch (info.method) {
            case PlaceMethod.UNIFORM:
              return this.doGenerateUniform(info);
            case PlaceMethod.ADAPTIVE:
              return this.doGenerateAdaptive(info);
            default:
              return [];
          }
        }
        static doGenerateUniform(info) {
          if (info.nProbesX < 2 || info.nProbesY < 2 || info.nProbesZ < 2) {
            return [];
          }
          const probes = [];
          const position = new Vec3(0.0, 0.0, 0.0);
          const gridSize = new Vec3((info.maxPos.x - info.minPos.x) / (info.nProbesX - 1), (info.maxPos.y - info.minPos.y) / (info.nProbesY - 1), (info.maxPos.z - info.minPos.z) / (info.nProbesZ - 1));
          for (let x = 0; x < info.nProbesX; x++) {
            position.x = x * gridSize.x + info.minPos.x;
            for (let y = 0; y < info.nProbesY; y++) {
              position.y = y * gridSize.y + info.minPos.y;
              for (let z = 0; z < info.nProbesZ; z++) {
                position.z = z * gridSize.z + info.minPos.z;
                probes.push(new Vec3(position));
              }
            }
          }
          return probes;
        }
        static doGenerateAdaptive(info) {
          return this.doGenerateUniform(info);
        }
      } exports("AutoPlacement", AutoPlacement);

      const Vertex$1 = exports("Vertex", jsb.Vertex);
      patch_cc_Vertex({
        Vertex: Vertex$1,
        Vec3
      });
      const CircumSphere = exports("CircumSphere", jsb.CircumSphere);
      patch_cc_CircumSphere({
        CircumSphere,
        Vec3
      });
      const Tetrahedron = exports("Tetrahedron", jsb.Tetrahedron);
      patch_cc_Tetrahedron({
        Tetrahedron,
        Mat3,
        Vec3,
        CircumSphere
      });

      const SH_BASIS_COUNT = 9;
      class LightProbeSampler {
        static uniformSampleSphere(u1, u2) {
          const z = 1.0 - 2.0 * u1;
          const r = Math.sqrt(Math.max(0.0, 1.0 - z * z));
          const phi = 2.0 * Math.PI * u2;
          const x = r * Math.cos(phi);
          const y = r * Math.sin(phi);
          return new Vec3(x, y, z);
        }
        static uniformSampleSphereAll(sampleCount) {
          assertIsTrue(sampleCount > 0);
          const uCount1 = Math.floor(Math.sqrt(sampleCount));
          const uCount2 = uCount1;
          const samples = [];
          const uDelta1 = 1.0 / uCount1;
          const uDelta2 = 1.0 / uCount2;
          for (let i = 0; i < uCount1; i++) {
            const u1 = (i + 0.5) * uDelta1;
            for (let j = 0; j < uCount2; j++) {
              const u2 = (j + 0.5) * uDelta2;
              const sample = this.uniformSampleSphere(u1, u2);
              samples.push(sample);
            }
          }
          return samples;
        }
        static uniformSpherePdf() {
          return 1.0 / (4.0 * Math.PI);
        }
      } exports("LightProbeSampler", LightProbeSampler);
      class SH {
        static updateUBOData(data, offset, coefficients) {
          data[offset++] = coefficients[3].x * this.basisOverPI[3];
          data[offset++] = coefficients[1].x * this.basisOverPI[1];
          data[offset++] = coefficients[2].x * this.basisOverPI[2];
          data[offset++] = coefficients[0].x * this.basisOverPI[0] - coefficients[6].x * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[3].y * this.basisOverPI[3];
          data[offset++] = coefficients[1].y * this.basisOverPI[1];
          data[offset++] = coefficients[2].y * this.basisOverPI[2];
          data[offset++] = coefficients[0].y * this.basisOverPI[0] - coefficients[6].y * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[3].z * this.basisOverPI[3];
          data[offset++] = coefficients[1].z * this.basisOverPI[1];
          data[offset++] = coefficients[2].z * this.basisOverPI[2];
          data[offset++] = coefficients[0].z * this.basisOverPI[0] - coefficients[6].z * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[4].x * this.basisOverPI[4];
          data[offset++] = coefficients[5].x * this.basisOverPI[5];
          data[offset++] = coefficients[6].x * this.basisOverPI[6];
          data[offset++] = coefficients[7].x * this.basisOverPI[7];
          data[offset++] = coefficients[4].y * this.basisOverPI[4];
          data[offset++] = coefficients[5].y * this.basisOverPI[5];
          data[offset++] = coefficients[6].y * this.basisOverPI[6];
          data[offset++] = coefficients[7].y * this.basisOverPI[7];
          data[offset++] = coefficients[4].z * this.basisOverPI[4];
          data[offset++] = coefficients[5].z * this.basisOverPI[5];
          data[offset++] = coefficients[6].z * this.basisOverPI[6];
          data[offset++] = coefficients[7].z * this.basisOverPI[7];
          data[offset++] = coefficients[8].x * this.basisOverPI[8];
          data[offset++] = coefficients[8].y * this.basisOverPI[8];
          data[offset++] = coefficients[8].z * this.basisOverPI[8];
          data[offset++] = 0.0;
        }
        static shaderEvaluate(normal, coefficients) {
          const linearConstR = new Vec4(coefficients[3].x * this.basisOverPI[3], coefficients[1].x * this.basisOverPI[1], coefficients[2].x * this.basisOverPI[2], coefficients[0].x * this.basisOverPI[0] - coefficients[6].x * this.basisOverPI[6] / 3.0);
          const linearConstG = new Vec4(coefficients[3].y * this.basisOverPI[3], coefficients[1].y * this.basisOverPI[1], coefficients[2].y * this.basisOverPI[2], coefficients[0].y * this.basisOverPI[0] - coefficients[6].y * this.basisOverPI[6] / 3.0);
          const linearConstB = new Vec4(coefficients[3].z * this.basisOverPI[3], coefficients[1].z * this.basisOverPI[1], coefficients[2].z * this.basisOverPI[2], coefficients[0].z * this.basisOverPI[0] - coefficients[6].z * this.basisOverPI[6] / 3.0);
          const quadraticR = new Vec4(coefficients[4].x * this.basisOverPI[4], coefficients[5].x * this.basisOverPI[5], coefficients[6].x * this.basisOverPI[6], coefficients[7].x * this.basisOverPI[7]);
          const quadraticG = new Vec4(coefficients[4].y * this.basisOverPI[4], coefficients[5].y * this.basisOverPI[5], coefficients[6].y * this.basisOverPI[6], coefficients[7].y * this.basisOverPI[7]);
          const quadraticB = new Vec4(coefficients[4].z * this.basisOverPI[4], coefficients[5].z * this.basisOverPI[5], coefficients[6].z * this.basisOverPI[6], coefficients[7].z * this.basisOverPI[7]);
          const quadraticA = new Vec3(coefficients[8].x * this.basisOverPI[8], coefficients[8].y * this.basisOverPI[8], coefficients[8].z * this.basisOverPI[8]);
          const result = new Vec3(0.0, 0.0, 0.0);
          const normal4 = new Vec4(normal.x, normal.y, normal.z, 1.0);
          result.x = Vec4.dot(linearConstR, normal4);
          result.y = Vec4.dot(linearConstG, normal4);
          result.z = Vec4.dot(linearConstB, normal4);
          const n14 = new Vec4(normal.x * normal.y, normal.y * normal.z, normal.z * normal.z, normal.z * normal.x);
          const n5 = normal.x * normal.x - normal.y * normal.y;
          result.x += Vec4.dot(quadraticR, n14);
          result.y += Vec4.dot(quadraticG, n14);
          result.z += Vec4.dot(quadraticB, n14);
          Vec3.scaleAndAdd(result, result, quadraticA, n5);
          return result;
        }
        static evaluate(sample, coefficients) {
          const result = new Vec3(0.0, 0.0, 0.0);
          const size = coefficients.length;
          for (let i = 0; i < size; i++) {
            const c = coefficients[i];
            Vec3.scaleAndAdd(result, result, c, this.evaluateBasis(i, sample));
          }
          return result;
        }
        static project(samples, values) {
          assertIsTrue(samples.length > 0 && samples.length === values.length);
          const basisCount = this.getBasisCount();
          const sampleCount = samples.length;
          const scale = 1.0 / (LightProbeSampler.uniformSpherePdf() * sampleCount);
          const coefficients = [];
          for (let i = 0; i < basisCount; i++) {
            const coefficient = new Vec3(0.0, 0.0, 0.0);
            for (let k = 0; k < sampleCount; k++) {
              Vec3.scaleAndAdd(coefficient, coefficient, values[k], this.evaluateBasis(i, samples[k]));
            }
            Vec3.multiplyScalar(coefficient, coefficient, scale);
            coefficients.push(coefficient);
          }
          return coefficients;
        }
        static convolveCosine(radianceCoefficients) {
          const cosTheta = [0.8862268925, 1.0233267546, 0.4954159260];
          const irradianceCoefficients = [];
          for (let l = 0; l <= this.LMAX; l++) {
            for (let m = -l; m <= l; m++) {
              const i = this.toIndex(l, m);
              const coefficient = new Vec3(0.0, 0.0, 0.0);
              Vec3.multiplyScalar(coefficient, radianceCoefficients[i], this.lambda(l) * cosTheta[l]);
              irradianceCoefficients.push(coefficient);
            }
          }
          return irradianceCoefficients;
        }
        static getBasisCount() {
          return SH_BASIS_COUNT;
        }
        static evaluateBasis(index, sample) {
          assertIsTrue(index < this.getBasisCount());
          const func = this.basisFunctions[index];
          return func(sample);
        }
        static reduceRinging(coefficients, lambda) {
          if (lambda === 0.0) {
            return;
          }
          for (let l = 0; l <= this.LMAX; ++l) {
            const scale = 1.0 / (1.0 + lambda * l * l * (l + 1) * (l + 1));
            for (let m = -l; m <= l; ++m) {
              const i = this.toIndex(l, m);
              Vec3.multiplyScalar(coefficients[i], coefficients[i], scale);
            }
          }
        }
        static lambda(l) {
          return Math.sqrt(4.0 * Math.PI / (2.0 * l + 1.0));
        }
        static toIndex(l, m) {
          return l * l + l + m;
        }
      } exports("SH", SH);
      SH.LMAX = 2;
      SH.basisFunctions = [v => 0.282095, v => 0.488603 * v.y, v => 0.488603 * v.z, v => 0.488603 * v.x, v => 1.09255 * v.y * v.x, v => 1.09255 * v.y * v.z, v => 0.946175 * (v.z * v.z - 1.0 / 3.0), v => 1.09255 * v.z * v.x, v => 0.546274 * (v.x * v.x - v.y * v.y)];
      SH.basisOverPI = [0.0897936, 0.155527, 0.155527, 0.155527, 0.347769, 0.347769, 0.301177, 0.347769, 0.173884];
      cclegacy.internal.SH = SH;

      const LightProbes = exports("LightProbes", jsb.LightProbes);
      ccclass$H('cc.LightProbes')(LightProbes);
      const LightProbesData = exports("LightProbesData", jsb.LightProbesData);
      patch_cc_LightProbesData({
        LightProbesData,
        Vertex: Vertex$1,
        Tetrahedron
      });

      var _dec$O, _dec2$J, _dec3$D, _dec4$t, _dec5$s, _dec6$l, _class$N, _class2$J, _initializer$I, _initializer2$D, _initializer3$v, _initializer4$s, _initializer5$n, _initializer6$j, _initializer7$f;
      let LightProbeGroup = exports("LightProbeGroup", (_dec$O = ccclass$H('cc.LightProbeGroup'), _dec2$J = type$a([Vec3]), _dec3$D = type$a(PlaceMethod), _dec4$t = type$a(CCInteger), _dec5$s = type$a(CCInteger), _dec6$l = type$a(CCInteger), _dec$O(_class$N = disallowMultiple$1(_class$N = (_class2$J = class LightProbeGroup extends Component {
        constructor(...args) {
          super(...args);
          this._probes = _initializer$I && _initializer$I();
          this._method = _initializer2$D && _initializer2$D();
          this._minPos = _initializer3$v && _initializer3$v();
          this._maxPos = _initializer4$s && _initializer4$s();
          this._nProbesX = _initializer5$n && _initializer5$n();
          this._nProbesY = _initializer6$j && _initializer6$j();
          this._nProbesZ = _initializer7$f && _initializer7$f();
        }
        get probes() {
          return this._probes;
        }
        set probes(val) {
          this._probes = val;
        }
        get method() {
          return this._method;
        }
        get minPos() {
          return this._minPos;
        }
        set minPos(val) {
          this._minPos = val;
        }
        get maxPos() {
          return this._maxPos;
        }
        set maxPos(val) {
          this._maxPos = val;
        }
        get nProbesX() {
          return this._nProbesX;
        }
        set nProbesX(val) {
          this._nProbesX = val;
        }
        get nProbesY() {
          return this._nProbesY;
        }
        set nProbesY(val) {
          this._nProbesY = val;
        }
        get nProbesZ() {
          return this._nProbesZ;
        }
        set nProbesZ(val) {
          this._nProbesZ = val;
        }
        onLoad() {
          {
            return;
          }
        }
        onEnable() {
          {
            return;
          }
        }
        onDisable() {
          {
            return;
          }
        }
        generateLightProbes() {
          if (!this.node) {
            return;
          }
          this._probes = AutoPlacement.generate({
            method: this._method,
            nProbesX: this._nProbesX,
            nProbesY: this._nProbesY,
            nProbesZ: this._nProbesZ,
            minPos: this._minPos,
            maxPos: this._maxPos
          });
          this.onProbeChanged();
        }
        onProbeChanged(updateTet = true, emitEvent = true) {
          this.node.scene.globals.lightProbeInfo.syncData(this.node, this.probes);
          this.node.scene.globals.lightProbeInfo.update(updateTet);
          if (emitEvent) {
            this.node.emit("light-probe-changed");
          }
        }
      }, (_initializer$I = applyDecoratedInitializer(_class2$J.prototype, "_probes", [serializable$l], function () {
        return [];
      }), _initializer2$D = applyDecoratedInitializer(_class2$J.prototype, "_method", [serializable$l], function () {
        return PlaceMethod.UNIFORM;
      }), _initializer3$v = applyDecoratedInitializer(_class2$J.prototype, "_minPos", [serializable$l], function () {
        return new Vec3(-5, -5, -5);
      }), _initializer4$s = applyDecoratedInitializer(_class2$J.prototype, "_maxPos", [serializable$l], function () {
        return new Vec3(5, 5, 5);
      }), _initializer5$n = applyDecoratedInitializer(_class2$J.prototype, "_nProbesX", [serializable$l], function () {
        return 3;
      }), _initializer6$j = applyDecoratedInitializer(_class2$J.prototype, "_nProbesY", [serializable$l], function () {
        return 3;
      }), _initializer7$f = applyDecoratedInitializer(_class2$J.prototype, "_nProbesZ", [serializable$l], function () {
        return 3;
      }), _applyDecoratedDescriptor(_class2$J.prototype, "probes", [_dec2$J], Object.getOwnPropertyDescriptor(_class2$J.prototype, "probes"), _class2$J.prototype), _applyDecoratedDescriptor(_class2$J.prototype, "method", [_dec3$D], Object.getOwnPropertyDescriptor(_class2$J.prototype, "method"), _class2$J.prototype), _applyDecoratedDescriptor(_class2$J.prototype, "nProbesX", [_dec4$t], Object.getOwnPropertyDescriptor(_class2$J.prototype, "nProbesX"), _class2$J.prototype), _applyDecoratedDescriptor(_class2$J.prototype, "nProbesY", [_dec5$s], Object.getOwnPropertyDescriptor(_class2$J.prototype, "nProbesY"), _class2$J.prototype), _applyDecoratedDescriptor(_class2$J.prototype, "nProbesZ", [_dec6$l], Object.getOwnPropertyDescriptor(_class2$J.prototype, "nProbesZ"), _class2$J.prototype)), _class2$J)) || _class$N) || _class$N));

      const DURATION_INFINITY = -1;
      const START_SIZE_EQUAL_TO_END_SIZE = -1;
      const START_RADIUS_EQUAL_TO_END_RADIUS = -1;
      const EmitterMode = Enum({
        GRAVITY: 0,
        RADIUS: 1
      });
      const PositionType = Enum({
        FREE: 0,
        RELATIVE: 1,
        GROUPED: 2
      });

      const _pos = new Vec2();
      const _tpa = new Vec2();
      const _tpb = new Vec2();
      const _tpc = new Vec2();
      const _col = new Vec4();
      const formatBytes = getComponentPerVertex(vfmtPosUvColor);
      function getWorldRotation(node) {
        let rotation = 0;
        let tempNode = node;
        while (tempNode) {
          rotation += tempNode.eulerAngles.z;
          tempNode = tempNode.parent;
        }
        return rotation;
      }
      class Particle {
        constructor() {
          this.pos = new Vec2(0, 0);
          this.startPos = new Vec2(0, 0);
          this.color = new Color$1(0, 0, 0, 255);
          this.deltaColor = {
            r: 0,
            g: 0,
            b: 0,
            a: 255
          };
          this.size = 0;
          this.deltaSize = 0;
          this.rotation = 0;
          this.deltaRotation = 0;
          this.timeToLive = 0;
          this.drawPos = new Vec2(0, 0);
          this.aspectRatio = 1;
          this.dir = new Vec2(0, 0);
          this.radialAccel = 0;
          this.tangentialAccel = 0;
          this.angle = 0;
          this.degreesPerSecond = 0;
          this.radius = 0;
          this.deltaRadius = 0;
        }
      }
      class ParticlePool extends Pool$1 {
        get() {
          return this._get() || new Particle();
        }
      }
      const pool = new ParticlePool(par => {
        par.pos.set(Vec2.ZERO);
        par.startPos.set(Vec2.ZERO);
        par.color.set(0, 0, 0, 255);
        par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
        par.deltaColor.a = 255;
        par.size = 0;
        par.deltaSize = 0;
        par.rotation = 0;
        par.deltaRotation = 0;
        par.timeToLive = 0;
        par.drawPos.set(Vec2.ZERO);
        par.aspectRatio = 1;
        par.dir.set(Vec2.ZERO);
        par.radialAccel = 0;
        par.tangentialAccel = 0;
        par.angle = 0;
        par.degreesPerSecond = 0;
        par.radius = 0;
        par.deltaRadius = 0;
      }, 1024);
      class Simulator {
        constructor(system) {
          this.particles = [];
          this.active = false;
          this.uvFilled = 0;
          this.finished = false;
          this.readyToPlay = true;
          this.elapsed = 0;
          this.emitCounter = 0;
          this._worldRotation = 0;
          this.sys = system;
          this.particles = [];
          this.active = false;
          this.readyToPlay = true;
          this.finished = false;
          this.elapsed = 0;
          this.emitCounter = 0;
          this.uvFilled = 0;
          this._worldRotation = 0;
        }
        stop() {
          this.active = false;
          this.readyToPlay = false;
          this.elapsed = this.sys.duration;
          this.emitCounter = 0;
        }
        reset() {
          this.active = true;
          this.readyToPlay = true;
          this.elapsed = 0;
          this.emitCounter = 0;
          this.finished = false;
          const particles = this.particles;
          for (let id = 0; id < particles.length; ++id) pool.put(particles[id]);
          particles.length = 0;
          if (this.renderData) this.renderData.resize(0, 0);
        }
        emitParticle(pos) {
          const psys = this.sys;
          const particle = pool.get();
          this.particles.push(particle);
          particle.timeToLive = psys.life + psys.lifeVar * (random() - 0.5) * 2;
          const timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive);
          particle.pos.x = psys.sourcePos.x + psys.posVar.x * (random() - 0.5) * 2;
          particle.pos.y = psys.sourcePos.y + psys.posVar.y * (random() - 0.5) * 2;
          let sr = 0;
          let sg = 0;
          let sb = 0;
          let sa = 0;
          const startColor = psys.startColor;
          const startColorVar = psys.startColorVar;
          const endColor = psys.endColor;
          const endColorVar = psys.endColorVar;
          particle.color.r = sr = clamp$1(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
          particle.color.g = sg = clamp$1(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
          particle.color.b = sb = clamp$1(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
          particle.color.a = sa = clamp$1(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
          particle.deltaColor.r = (clamp$1(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
          particle.deltaColor.g = (clamp$1(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
          particle.deltaColor.b = (clamp$1(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
          particle.deltaColor.a = (clamp$1(endColor.a + endColorVar.a * (random() - 0.5) * 2, 0, 255) - sa) / timeToLive;
          let startS = psys.startSize + psys.startSizeVar * (random() - 0.5) * 2;
          startS = Math.max(0, startS);
          particle.size = startS;
          if (psys.endSize === START_SIZE_EQUAL_TO_END_SIZE) {
            particle.deltaSize = 0;
          } else {
            let endS = psys.endSize + psys.endSizeVar * (random() - 0.5) * 2;
            endS = Math.max(0, endS);
            particle.deltaSize = (endS - startS) / timeToLive;
          }
          const startA = psys.startSpin + psys.startSpinVar * (random() - 0.5) * 2;
          const endA = psys.endSpin + psys.endSpinVar * (random() - 0.5) * 2;
          particle.rotation = startA;
          particle.deltaRotation = (endA - startA) / timeToLive;
          particle.startPos.x = pos.x;
          particle.startPos.y = pos.y;
          particle.aspectRatio = psys.aspectRatio || 1;
          const a = toRadian(psys.angle + this._worldRotation + psys.angleVar * (random() - 0.5) * 2);
          if (psys.emitterMode === EmitterMode.GRAVITY) {
            const s = psys.speed + psys.speedVar * (random() - 0.5) * 2;
            particle.dir.x = Math.cos(a);
            particle.dir.y = Math.sin(a);
            particle.dir.multiplyScalar(s);
            particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (random() - 0.5) * 2;
            particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (random() - 0.5) * 2;
            if (psys.rotationIsDir) {
              particle.rotation = -toDegree(Math.atan2(particle.dir.y, particle.dir.x));
            }
          } else {
            const startRadius = psys.startRadius + psys.startRadiusVar * (random() - 0.5) * 2;
            const endRadius = psys.endRadius + psys.endRadiusVar * (random() - 0.5) * 2;
            particle.radius = startRadius;
            particle.deltaRadius = psys.endRadius === START_RADIUS_EQUAL_TO_END_RADIUS ? 0 : (endRadius - startRadius) / timeToLive;
            particle.angle = a;
            particle.degreesPerSecond = toRadian(psys.rotatePerS + psys.rotatePerSVar * (random() - 0.5) * 2);
          }
        }
        updateUVs(force) {
          const renderData = this.renderData;
          if (renderData && this.sys._renderSpriteFrame) {
            const vbuf = renderData.vData;
            const uv = this.sys._renderSpriteFrame.uv;
            const start = force ? 0 : this.uvFilled;
            const particleCount = this.particles.length;
            for (let i = start; i < particleCount; i++) {
              const offset = i * formatBytes * 4;
              vbuf[offset + 3] = uv[0];
              vbuf[offset + 4] = uv[1];
              vbuf[offset + 12] = uv[2];
              vbuf[offset + 13] = uv[3];
              vbuf[offset + 21] = uv[4];
              vbuf[offset + 22] = uv[5];
              vbuf[offset + 30] = uv[6];
              vbuf[offset + 31] = uv[7];
            }
            this.uvFilled = particleCount;
          }
        }
        updateParticleBuffer(particle, pos, buffer, offset) {
          const vbuf = buffer.vData;
          const x = pos.x;
          const y = pos.y;
          let width = particle.size;
          let height = width;
          const aspectRatio = particle.aspectRatio;
          if (aspectRatio > 1) {
            height = width / aspectRatio;
          } else {
            width = height * aspectRatio;
          }
          const halfWidth = width / 2;
          const halfHeight = height / 2;
          if (particle.rotation) {
            const x1 = -halfWidth;
            const y1 = -halfHeight;
            const x2 = halfWidth;
            const y2 = halfHeight;
            const rad = -toRadian(particle.rotation);
            const cr = Math.cos(rad);
            const sr = Math.sin(rad);
            vbuf[offset] = x1 * cr - y1 * sr + x;
            vbuf[offset + 1] = x1 * sr + y1 * cr + y;
            vbuf[offset + 2] = 0;
            vbuf[offset + 9] = x2 * cr - y1 * sr + x;
            vbuf[offset + 10] = x2 * sr + y1 * cr + y;
            vbuf[offset + 11] = 0;
            vbuf[offset + 18] = x1 * cr - y2 * sr + x;
            vbuf[offset + 19] = x1 * sr + y2 * cr + y;
            vbuf[offset + 20] = 0;
            vbuf[offset + 27] = x2 * cr - y2 * sr + x;
            vbuf[offset + 28] = x2 * sr + y2 * cr + y;
            vbuf[offset + 29] = 0;
          } else {
            vbuf[offset] = x - halfWidth;
            vbuf[offset + 1] = y - halfHeight;
            vbuf[offset + 2] = 0;
            vbuf[offset + 9] = x + halfWidth;
            vbuf[offset + 10] = y - halfHeight;
            vbuf[offset + 11] = 0;
            vbuf[offset + 18] = x - halfWidth;
            vbuf[offset + 19] = y + halfHeight;
            vbuf[offset + 20] = 0;
            vbuf[offset + 27] = x + halfWidth;
            vbuf[offset + 28] = y + halfHeight;
            vbuf[offset + 29] = 0;
          }
          const pcol = particle.color;
          _col.x = pcol.r / 255;
          _col.y = pcol.g / 255;
          _col.z = pcol.b / 255;
          _col.w = pcol.a / 255;
          Vec4.toArray(vbuf, _col, offset + 5);
          Vec4.toArray(vbuf, _col, offset + 14);
          Vec4.toArray(vbuf, _col, offset + 23);
          Vec4.toArray(vbuf, _col, offset + 32);
        }
        step(dt) {
          const assembler = this.sys.assembler;
          const psys = this.sys;
          const node = psys.node;
          const particles = this.particles;
          dt = dt > assembler.maxParticleDeltaTime ? assembler.maxParticleDeltaTime : dt;
          node.updateWorldTransform();
          if (psys.positionType === PositionType.FREE) {
            this._worldRotation = getWorldRotation(node);
            const m = node.worldMatrix;
            _pos.x = m.m12;
            _pos.y = m.m13;
          } else if (psys.positionType === PositionType.RELATIVE) {
            this._worldRotation = node.eulerAngles.z;
            _pos.x = node.position.x;
            _pos.y = node.position.y;
          } else {
            this._worldRotation = 0;
          }
          if (this.active && psys.emissionRate) {
            const rate = 1.0 / psys.emissionRate;
            if (particles.length < psys.totalParticles) this.emitCounter += dt;
            while (particles.length < psys.totalParticles && this.emitCounter > rate) {
              this.emitParticle(_pos);
              this.emitCounter -= rate;
            }
            this.elapsed += dt;
            if (psys.duration !== -1 && psys.duration < this.elapsed) {
              psys.stopSystem();
            }
          }
          const renderData = this.renderData;
          const particleCount = particles.length;
          renderData.reset();
          this.requestData(particleCount * 4, particleCount * 6);
          if (particleCount > this.uvFilled) {
            this.updateUVs();
          }
          let particleIdx = 0;
          while (particleIdx < particles.length) {
            _tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0;
            const particle = particles[particleIdx];
            particle.timeToLive -= dt;
            if (particle.timeToLive > 0) {
              if (psys.emitterMode === EmitterMode.GRAVITY) {
                const tmp = _tpc;
                const radial = _tpa;
                const tangential = _tpb;
                if (particle.pos.x || particle.pos.y) {
                  radial.set(particle.pos);
                  radial.normalize();
                }
                tangential.set(radial);
                radial.multiplyScalar(particle.radialAccel);
                const newy = tangential.x;
                tangential.x = -tangential.y;
                tangential.y = newy;
                tangential.multiplyScalar(particle.tangentialAccel);
                tmp.set(radial);
                tmp.add(tangential);
                tmp.add(psys.gravity);
                tmp.multiplyScalar(dt);
                particle.dir.add(tmp);
                tmp.set(particle.dir);
                tmp.multiplyScalar(dt);
                particle.pos.add(tmp);
              } else {
                particle.angle += particle.degreesPerSecond * dt;
                particle.radius += particle.deltaRadius * dt;
                particle.pos.x = -Math.cos(particle.angle) * particle.radius;
                particle.pos.y = -Math.sin(particle.angle) * particle.radius;
              }
              particle.color.r += particle.deltaColor.r * dt;
              particle.color.g += particle.deltaColor.g * dt;
              particle.color.b += particle.deltaColor.b * dt;
              particle.color.a += particle.deltaColor.a * dt;
              particle.size += particle.deltaSize * dt;
              if (particle.size < 0) {
                particle.size = 0;
              }
              particle.rotation += particle.deltaRotation * dt;
              const newPos = _tpa;
              newPos.set(particle.pos);
              if (psys.positionType !== PositionType.GROUPED) {
                newPos.add(particle.startPos);
              }
              const offset = formatBytes * particleIdx * 4;
              this.updateParticleBuffer(particle, newPos, renderData, offset);
              ++particleIdx;
            } else {
              const deadParticle = particles[particleIdx];
              if (particleIdx !== particles.length - 1) {
                particles[particleIdx] = particles[particles.length - 1];
              }
              pool.put(deadParticle);
              particles.length--;
              renderData.resize(renderData.vertexCount - 4, renderData.indexCount - 6);
            }
          }
          this.renderData.material = this.sys.getRenderMaterial(0);
          this.renderData.frame = this.sys._renderSpriteFrame;
          renderData.setRenderDrawInfoAttributes();
          if (particles.length === 0 && !this.active && !this.readyToPlay) {
            this.finished = true;
            psys._finishedSimulation();
          }
        }
        requestData(vertexCount, indexCount) {
          let offset = this.renderData.indexCount;
          this.renderData.request(vertexCount, indexCount);
          const count = this.renderData.indexCount / 6;
          const buffer = this.renderData.iData;
          for (let i = offset; i < count; i++) {
            const vId = i * 4;
            buffer[offset++] = vId;
            buffer[offset++] = vId + 1;
            buffer[offset++] = vId + 2;
            buffer[offset++] = vId + 1;
            buffer[offset++] = vId + 3;
            buffer[offset++] = vId + 2;
          }
        }
        initDrawInfo() {
          const renderData = this.renderData;
          renderData.setRenderDrawInfoAttributes();
        }
      }

      var _dec$N, _class$M, _class2$I, _initializer$H;
      const {
        ccclass: ccclass$f,
        serializable: serializable$1,
        editable: editable$2
      } = _decorator;
      let ParticleAsset = exports("ParticleAsset", (_dec$N = ccclass$f('cc.ParticleAsset'), _dec$N(_class$M = (_class2$I = class ParticleAsset extends Asset {
        constructor(...args) {
          super(...args);
          this.spriteFrame = _initializer$H && _initializer$H();
        }
      }, (_initializer$H = applyDecoratedInitializer(_class2$I.prototype, "spriteFrame", [serializable$1], function () {
        return null;
      })), _class2$I)) || _class$M));
      cclegacy.ParticleAsset = ParticleAsset;

      var ns$1 = {};
      (function () {

        function m(a) {
          throw a;
        }
        var q = void 0,
          aa = this;
        function s(a, c) {
          var d = a.split("."),
            b = aa;
          !(d[0] in b) && b.execScript && b.execScript("var " + d[0]);
          for (var e; d.length && (e = d.shift());) !d.length && c !== q ? b[e] = c : b = b[e] ? b[e] : b[e] = {};
        }
        var u = "undefined" !== typeof Uint8Array && "undefined" !== typeof Uint16Array && "undefined" !== typeof Uint32Array && "undefined" !== typeof DataView;
        function x(a) {
          var c = a.length,
            d = 0,
            b = Number.POSITIVE_INFINITY,
            e,
            g,
            f,
            l,
            h,
            k,
            n,
            p,
            t,
            y;
          for (p = 0; p < c; ++p) a[p] > d && (d = a[p]), a[p] < b && (b = a[p]);
          e = 1 << d;
          g = new (u ? Uint32Array : Array)(e);
          f = 1;
          l = 0;
          for (h = 2; f <= d;) {
            for (p = 0; p < c; ++p) if (a[p] === f) {
              k = 0;
              n = l;
              for (t = 0; t < f; ++t) k = k << 1 | n & 1, n >>= 1;
              y = f << 16 | p;
              for (t = k; t < e; t += h) g[t] = y;
              ++l;
            }
            ++f;
            l <<= 1;
            h <<= 1;
          }
          return [g, d, b];
        }
        function ba(a, c) {
          this.g = [];
          this.h = 32768;
          this.d = this.f = this.a = this.j = 0;
          this.input = u ? new Uint8Array(a) : a;
          this.k = !1;
          this.e = z;
          this.o = !1;
          if (c || !(c = {})) c.index && (this.a = c.index), c.bufferSize && (this.h = c.bufferSize), c.bufferType && (this.e = c.bufferType), c.resize && (this.o = c.resize);
          switch (this.e) {
            case A:
              this.b = 32768;
              this.c = new (u ? Uint8Array : Array)(32768 + this.h + 258);
              break;
            case z:
              this.b = 0;
              this.c = new (u ? Uint8Array : Array)(this.h);
              break;
            default:
              m(Error("invalid inflate mode"));
          }
        }
        var A = 0,
          z = 1,
          ca = {
            q: A,
            p: z
          };
        ba.prototype.i = function () {
          for (; !this.k;) {
            var a = B(this, 3);
            a & 1 && (this.k = !0);
            a >>>= 1;
            switch (a) {
              case 0:
                var c = this.input,
                  d = this.a,
                  b = this.c,
                  e = this.b,
                  g = c.length,
                  f = q,
                  l = q,
                  h = b.length,
                  k = q;
                this.d = this.f = 0;
                d + 1 >= g && m(Error("invalid uncompressed block header: LEN"));
                f = c[d++] | c[d++] << 8;
                d + 1 >= g && m(Error("invalid uncompressed block header: NLEN"));
                l = c[d++] | c[d++] << 8;
                f === ~l && m(Error("invalid uncompressed block header: length verify"));
                d + f > c.length && m(Error("input buffer is broken"));
                switch (this.e) {
                  case A:
                    for (; e + f > b.length;) {
                      k = h - e;
                      f -= k;
                      if (u) b.set(c.subarray(d, d + k), e), e += k, d += k;else for (; k--;) b[e++] = c[d++];
                      this.b = e;
                      b = D(this);
                      e = this.b;
                    }
                    break;
                  case z:
                    for (; e + f > b.length;) b = E(this, {
                      m: 2
                    });
                    break;
                  default:
                    m(Error("invalid inflate mode"));
                }
                if (u) b.set(c.subarray(d, d + f), e), e += f, d += f;else for (; f--;) b[e++] = c[d++];
                this.a = d;
                this.b = e;
                this.c = b;
                break;
              case 1:
                switch (this.e) {
                  case z:
                    da(this, ea, fa);
                    break;
                  case A:
                    ga(this, ea, fa);
                    break;
                  default:
                    m(Error("invalid inflate mode"));
                }
                break;
              case 2:
                for (var n = B(this, 5) + 257, p = B(this, 5) + 1, t = B(this, 4) + 4, y = new (u ? Uint8Array : Array)(H.length), ja = q, T = q, U = q, v = q, V = q, J = q, C = q, r = q, ka = q, r = 0; r < t; ++r) y[H[r]] = B(this, 3);
                if (!u) {
                  r = t;
                  for (t = y.length; r < t; ++r) y[H[r]] = 0;
                }
                ja = x(y);
                v = new (u ? Uint8Array : Array)(n + p);
                r = 0;
                for (ka = n + p; r < ka;) switch (V = I(this, ja), V) {
                  case 16:
                    for (C = 3 + B(this, 2); C--;) v[r++] = J;
                    break;
                  case 17:
                    for (C = 3 + B(this, 3); C--;) v[r++] = 0;
                    J = 0;
                    break;
                  case 18:
                    for (C = 11 + B(this, 7); C--;) v[r++] = 0;
                    J = 0;
                    break;
                  default:
                    J = v[r++] = V;
                }
                T = u ? x(v.subarray(0, n)) : x(v.slice(0, n));
                U = u ? x(v.subarray(n)) : x(v.slice(n));
                switch (this.e) {
                  case z:
                    da(this, T, U);
                    break;
                  case A:
                    ga(this, T, U);
                    break;
                  default:
                    m(Error("invalid inflate mode"));
                }
                break;
              default:
                m(Error("unknown BTYPE: " + a));
            }
          }
          switch (this.e) {
            case A:
              var W;
              var la = 0,
                za = this.c,
                X = this.g,
                Y,
                Z = new (u ? Uint8Array : Array)(this.j + (this.b - 32768)),
                w,
                K,
                L,
                ma;
              if (0 === X.length) W = u ? this.c.subarray(32768, this.b) : this.c.slice(32768, this.b);else {
                w = 0;
                for (K = X.length; w < K; ++w) {
                  Y = X[w];
                  L = 0;
                  for (ma = Y.length; L < ma; ++L) Z[la++] = Y[L];
                }
                w = 32768;
                for (K = this.b; w < K; ++w) Z[la++] = za[w];
                this.g = [];
                W = this.buffer = Z;
              }
              return W;
            case z:
              var F,
                G = this.b;
              u ? this.o ? (F = new Uint8Array(G), F.set(this.c.subarray(0, G))) : F = this.c.subarray(0, G) : (this.c.length > G && (this.c.length = G), F = this.c);
              return this.buffer = F;
            default:
              m(Error("invalid inflate mode"));
          }
        };
        var ha = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
          H = u ? new Uint16Array(ha) : ha,
          ia = [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],
          na = u ? new Uint16Array(ia) : ia,
          oa = [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],
          M = u ? new Uint8Array(oa) : oa,
          pa = [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],
          qa = u ? new Uint16Array(pa) : pa,
          ra = [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],
          N = u ? new Uint8Array(ra) : ra,
          O = new (u ? Uint8Array : Array)(288),
          P,
          sa;
        P = 0;
        for (sa = O.length; P < sa; ++P) O[P] = 143 >= P ? 8 : 255 >= P ? 9 : 279 >= P ? 7 : 8;
        var ea = x(O),
          ta = new (u ? Uint8Array : Array)(30),
          Q,
          ua;
        Q = 0;
        for (ua = ta.length; Q < ua; ++Q) ta[Q] = 5;
        var fa = x(ta);
        function B(a, c) {
          var d = a.f,
            b = a.d,
            e = a.input,
            g = a.a,
            f;
          g + (c - b + 7 >> 3) >= e.length && m(Error("input buffer is broken"));
          for (; b < c;) d |= e[g++] << b, b += 8;
          f = d & (1 << c) - 1;
          a.f = d >>> c;
          a.d = b - c;
          a.a = g;
          return f;
        }
        function I(a, c) {
          for (var d = a.f, b = a.d, e = a.input, g = a.a, f = e.length, l = c[0], h = c[1], k, n; b < h && !(g >= f);) d |= e[g++] << b, b += 8;
          k = l[d & (1 << h) - 1];
          n = k >>> 16;
          n > b && m(Error("invalid code length: " + n));
          a.f = d >> n;
          a.d = b - n;
          a.a = g;
          return k & 65535;
        }
        function ga(a, c, d) {
          var b = a.c,
            e = a.b;
          a.l = c;
          for (var g = b.length - 258, f, l, h, k; 256 !== (f = I(a, c));) if (256 > f) e >= g && (a.b = e, b = D(a), e = a.b), b[e++] = f;else {
            l = f - 257;
            k = na[l];
            0 < M[l] && (k += B(a, M[l]));
            f = I(a, d);
            h = qa[f];
            0 < N[f] && (h += B(a, N[f]));
            e >= g && (a.b = e, b = D(a), e = a.b);
            for (; k--;) b[e] = b[e++ - h];
          }
          for (; 8 <= a.d;) a.d -= 8, a.a--;
          a.b = e;
        }
        function da(a, c, d) {
          var b = a.c,
            e = a.b;
          a.l = c;
          for (var g = b.length, f, l, h, k; 256 !== (f = I(a, c));) if (256 > f) e >= g && (b = E(a), g = b.length), b[e++] = f;else {
            l = f - 257;
            k = na[l];
            0 < M[l] && (k += B(a, M[l]));
            f = I(a, d);
            h = qa[f];
            0 < N[f] && (h += B(a, N[f]));
            e + k > g && (b = E(a), g = b.length);
            for (; k--;) b[e] = b[e++ - h];
          }
          for (; 8 <= a.d;) a.d -= 8, a.a--;
          a.b = e;
        }
        function D(a) {
          var c = new (u ? Uint8Array : Array)(a.b - 32768),
            d = a.b - 32768,
            b,
            e,
            g = a.c;
          if (u) c.set(g.subarray(32768, c.length));else {
            b = 0;
            for (e = c.length; b < e; ++b) c[b] = g[b + 32768];
          }
          a.g.push(c);
          a.j += c.length;
          if (u) g.set(g.subarray(d, d + 32768));else for (b = 0; 32768 > b; ++b) g[b] = g[d + b];
          a.b = 32768;
          return g;
        }
        function E(a, c) {
          var d,
            b = a.input.length / a.a + 1 | 0,
            e,
            g,
            f,
            l = a.input,
            h = a.c;
          c && ("number" === typeof c.m && (b = c.m), "number" === typeof c.r && (b += c.r));
          2 > b ? (e = (l.length - a.a) / a.l[2], f = 258 * (e / 2) | 0, g = f < h.length ? h.length + f : h.length << 1) : g = h.length * b;
          u ? (d = new Uint8Array(g), d.set(h)) : d = h;
          a.c = d;
          return a.c;
        }
        function va(a, c) {
          var d, b;
          this.input = a;
          this.a = 0;
          if (c || !(c = {})) c.index && (this.a = c.index), c.verify && (this.s = c.verify);
          d = a[this.a++];
          b = a[this.a++];
          switch (d & 15) {
            case wa:
              this.method = wa;
              break;
            default:
              m(Error("unsupported compression method"));
          }
          0 !== ((d << 8) + b) % 31 && m(Error("invalid fcheck flag:" + ((d << 8) + b) % 31));
          b & 32 && m(Error("fdict flag is not supported"));
          this.n = new ba(a, {
            index: this.a,
            bufferSize: c.bufferSize,
            bufferType: c.bufferType,
            resize: c.resize
          });
        }
        va.prototype.i = function () {
          var a = this.input,
            c,
            d;
          c = this.n.i();
          this.a = this.n.a;
          if (this.s) {
            d = (a[this.a++] << 24 | a[this.a++] << 16 | a[this.a++] << 8 | a[this.a++]) >>> 0;
            var b = c;
            if ("string" === typeof b) {
              var e = b.split(""),
                g,
                f;
              g = 0;
              for (f = e.length; g < f; g++) e[g] = (e[g].charCodeAt(0) & 255) >>> 0;
              b = e;
            }
            for (var l = 1, h = 0, k = b.length, n, p = 0; 0 < k;) {
              n = 1024 < k ? 1024 : k;
              k -= n;
              do l += b[p++], h += l; while (--n);
              l %= 65521;
              h %= 65521;
            }
            d !== (h << 16 | l) >>> 0 && m(Error("invalid adler-32 checksum"));
          }
          return c;
        };
        var wa = 8;
        s("Zlib.Inflate", va);
        s("Zlib.Inflate.prototype.decompress", va.prototype.i);
        var xa = {
            ADAPTIVE: ca.p,
            BLOCK: ca.q
          },
          R,
          S,
          $,
          ya;
        if (Object.keys) R = Object.keys(xa);else for (S in R = [], $ = 0, xa) R[$++] = S;
        $ = 0;
        for (ya = R.length; $ < ya; ++$) S = R[$], s("Zlib.Inflate.BufferType." + S, xa[S]);
      }).call(ns$1);
      var _p = ns$1.Zlib;
      _p.Inflate = _p["Inflate"];
      _p.Inflate.BufferType = _p.Inflate["BufferType"];
      _p.Inflate.prototype.decompress = _p.Inflate.prototype["decompress"];

      class PNGReader {
        constructor(data) {
          this.pos = 8;
          this.palette = [];
          this.imgData = [];
          this.text = {};
          this.width = 0;
          this.height = 0;
          this.bits = 0;
          this.colorType = 0;
          this.compressionMethod = 0;
          this.filterMethod = 0;
          this.interlaceMethod = 0;
          this.colors = 0;
          this.hasAlphaChannel = false;
          this.pixelBitlength = 0;
          this.data = data;
          this.transparency = {
            indexed: [],
            rgb: 0,
            grayscale: 0
          };
          let frame;
          let _i = 0;
          let _j = 0;
          let chunkSize = 0;
          while (true) {
            chunkSize = this.readUInt32();
            const section = (() => {
              const _results = [];
              for (_i = 0; _i < 4; ++_i) {
                _results.push(String.fromCharCode(this.data[this.pos++]));
              }
              return _results;
            }).call(this).join('');
            switch (section) {
              case 'IHDR':
                this.width = this.readUInt32();
                this.height = this.readUInt32();
                this.bits = this.data[this.pos++];
                this.colorType = this.data[this.pos++];
                this.compressionMethod = this.data[this.pos++];
                this.filterMethod = this.data[this.pos++];
                this.interlaceMethod = this.data[this.pos++];
                break;
              case 'acTL':
                this.animation = {
                  numFrames: this.readUInt32(),
                  numPlays: this.readUInt32() || Infinity,
                  frames: []
                };
                break;
              case 'PLTE':
                this.palette = this.read(chunkSize);
                break;
              case 'fcTL':
                if (frame) {
                  this.animation.frames.push(frame);
                }
                this.pos += 4;
                frame = {
                  width: this.readUInt32(),
                  height: this.readUInt32(),
                  xOffset: this.readUInt32(),
                  yOffset: this.readUInt32()
                };
                const delayNum = this.readUInt16();
                const delayDen = this.readUInt16() || 100;
                frame.delay = 1000 * delayNum / delayDen;
                frame.disposeOp = this.data[this.pos++];
                frame.blendOp = this.data[this.pos++];
                frame.data = [];
                break;
              case 'IDAT':
              case 'fdAT':
                if (section === 'fdAT') {
                  this.pos += 4;
                  chunkSize -= 4;
                }
                data = (frame != null ? frame.data : void 0) || this.imgData;
                for (_i = 0; chunkSize >= 0 ? _i < chunkSize : _i > chunkSize; chunkSize >= 0 ? ++_i : --_i) {
                  data.push(this.data[this.pos++]);
                }
                break;
              case 'tRNS':
                this.transparency = {};
                switch (this.colorType) {
                  case 3:
                    this.transparency.indexed = this.read(chunkSize);
                    const ccshort = 255 - this.transparency.indexed.length;
                    if (ccshort > 0) {
                      for (_j = 0; ccshort >= 0 ? _j < ccshort : _j > ccshort; ccshort >= 0 ? ++_j : --_j) {
                        this.transparency.indexed.push(255);
                      }
                    }
                    break;
                  case 0:
                    this.transparency.grayscale = this.read(chunkSize)[0];
                    break;
                  case 2:
                    this.transparency.rgb = this.read(chunkSize);
                }
                break;
              case 'tEXt':
                const text = this.read(chunkSize);
                const index = text.indexOf(0);
                const key = String.fromCharCode.apply(String, text.slice(0, index));
                this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
                break;
              case 'IEND':
                if (frame) {
                  this.animation.frames.push(frame);
                }
                this.colors = (() => {
                  switch (this.colorType) {
                    case 0:
                    case 3:
                    case 4:
                      return 1;
                    case 2:
                    case 6:
                      return 3;
                  }
                }).call(this);
                const _ref = this.colorType;
                this.hasAlphaChannel = _ref === 4 || _ref === 6;
                const colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
                this.pixelBitlength = this.bits * colors;
                this.colorSpace = (() => {
                  switch (this.colors) {
                    case 1:
                      return 'DeviceGray';
                    case 3:
                      return 'DeviceRGB';
                  }
                }).call(this);
                if (!(this.imgData instanceof Uint8Array)) {
                  this.imgData = new Uint8Array(this.imgData);
                }
                return;
              default:
                this.pos += chunkSize;
            }
            this.pos += 4;
            if (this.pos > this.data.length) {
              throw new Error(getError(6017));
            }
          }
        }
        read(bytes) {
          let _i = 0;
          const _results = [];
          for (_i = 0; bytes >= 0 ? _i < bytes : _i > bytes; bytes >= 0 ? ++_i : --_i) {
            _results.push(this.data[this.pos++]);
          }
          return _results;
        }
        readUInt32() {
          const b1 = this.data[this.pos++] << 24;
          const b2 = this.data[this.pos++] << 16;
          const b3 = this.data[this.pos++] << 8;
          const b4 = this.data[this.pos++];
          return b1 | b2 | b3 | b4;
        }
        readUInt16() {
          const b1 = this.data[this.pos++] << 8;
          const b2 = this.data[this.pos++];
          return b1 | b2;
        }
        decodePixels(data) {
          if (data == null) {
            data = this.imgData;
          }
          if (data.length === 0) {
            return new Uint8Array(0);
          }
          const inflate = new _p.Inflate(data, {
            index: 0,
            verify: false
          });
          data = inflate.decompress();
          const pixelBytes = this.pixelBitlength / 8;
          const scanlineLength = pixelBytes * this.width;
          const pixels = new Uint8Array(scanlineLength * this.height);
          const length = data.length;
          let row = 0;
          let pos = 0;
          let c = 0;
          let ccbyte = 0;
          let col = 0;
          let i = 0;
          let _i = 0;
          let _j = 0;
          let _k = 0;
          let _l = 0;
          let _m = 0;
          let left = 0;
          let p = 0;
          let pa = 0;
          let paeth = 0;
          let pb = 0;
          let pc = 0;
          let upper = 0;
          let upperLeft = 0;
          while (pos < length) {
            switch (data[pos++]) {
              case 0:
                for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
                  pixels[c++] = data[pos++];
                }
                break;
              case 1:
                for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
                  ccbyte = data[pos++];
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  pixels[c++] = (ccbyte + left) % 256;
                }
                break;
              case 2:
                for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                  pixels[c++] = (upper + ccbyte) % 256;
                }
                break;
              case 3:
                for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                  pixels[c++] = (ccbyte + Math.floor((left + upper) / 2)) % 256;
                }
                break;
              case 4:
                for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  if (row === 0) {
                    upper = upperLeft = 0;
                  } else {
                    upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                    upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes];
                  }
                  p = left + upper - upperLeft;
                  pa = Math.abs(p - left);
                  pb = Math.abs(p - upper);
                  pc = Math.abs(p - upperLeft);
                  if (pa <= pb && pa <= pc) {
                    paeth = left;
                  } else if (pb <= pc) {
                    paeth = upper;
                  } else {
                    paeth = upperLeft;
                  }
                  pixels[c++] = (ccbyte + paeth) % 256;
                }
                break;
              default:
                throw new Error(getError(6018, data[pos - 1]));
            }
            row++;
          }
          return pixels;
        }
        copyToImageData(imageData, pixels) {
          let alpha = this.hasAlphaChannel;
          let palette;
          let colors = this.colors;
          if (this.palette.length) {
            palette = this._decodedPalette != null ? this._decodedPalette : this._decodedPalette = this.decodePalette();
            colors = 4;
            alpha = true;
          }
          const data = imageData.data || imageData;
          const length = data.length;
          const input = palette || pixels;
          let i = 0;
          let j = 0;
          let k = 0;
          let v = 0;
          if (colors === 1) {
            while (i < length) {
              k = palette ? pixels[i / 4] * 4 : j;
              v = input[k++];
              data[i++] = v;
              data[i++] = v;
              data[i++] = v;
              data[i++] = alpha ? input[k++] : 255;
              j = k;
            }
          } else {
            while (i < length) {
              k = palette ? pixels[i / 4] * 4 : j;
              data[i++] = input[k++];
              data[i++] = input[k++];
              data[i++] = input[k++];
              data[i++] = alpha ? input[k++] : 255;
              j = k;
            }
          }
        }
        decodePalette() {
          const palette = this.palette;
          const transparency = this.transparency.indexed || [];
          const ret = new Uint8Array((transparency.length || 0) + palette.length);
          let pos = 0;
          let c = 0;
          let _ref1 = 0;
          for (let i = 0, _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
            ret[pos++] = palette[i];
            ret[pos++] = palette[i + 1];
            ret[pos++] = palette[i + 2];
            _ref1 = transparency[c++];
            ret[pos++] = _ref1 != null ? _ref1 : 255;
          }
          return ret;
        }
        render(canvas) {
          canvas.width = this.width;
          canvas.height = this.height;
          const ctx = canvas.getContext('2d');
          const data = ctx.createImageData(this.width, this.height);
          this.copyToImageData(data, this.decodePixels(null));
          return ctx.putImageData(data, 0, 0);
        }
      }

      class TiffReader {
        constructor() {
          this._littleEndian = false;
          this._tiffData = [];
          this._fileDirectories = [];
        }
        getUint8(offset) {
          return this._tiffData[offset];
        }
        getUint16(offset) {
          if (this._littleEndian) return this._tiffData[offset + 1] << 8 | this._tiffData[offset];else return this._tiffData[offset] << 8 | this._tiffData[offset + 1];
        }
        getUint32(offset) {
          const a = this._tiffData;
          if (this._littleEndian) return a[offset + 3] << 24 | a[offset + 2] << 16 | a[offset + 1] << 8 | a[offset];else return a[offset] << 24 | a[offset + 1] << 16 | a[offset + 2] << 8 | a[offset + 3];
        }
        checkLittleEndian() {
          const BOM = this.getUint16(0);
          if (BOM === 0x4949) {
            this._littleEndian = true;
          } else if (BOM === 0x4D4D) {
            this._littleEndian = false;
          } else {
            console.log(BOM);
            throw TypeError(getError(6019));
          }
          return this._littleEndian;
        }
        hasTowel() {
          if (this.getUint16(2) !== 42) {
            throw RangeError(getError(6020));
          }
          return true;
        }
        getFieldTypeName(fieldType) {
          const typeNames = fieldTypeNames;
          if (fieldType in typeNames) {
            return typeNames[fieldType];
          }
          return null;
        }
        getFieldTagName(fieldTag) {
          const tagNames = fieldTagNames;
          if (fieldTag in tagNames) {
            return tagNames[fieldTag];
          } else {
            logID(6021, fieldTag);
            return `Tag${fieldTag}`;
          }
        }
        getFieldTypeLength(fieldTypeName) {
          if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) {
            return 1;
          } else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) {
            return 2;
          } else if (['LONG', 'SLONG', 'FLOAT'].indexOf(fieldTypeName) !== -1) {
            return 4;
          } else if (['RATIONAL', 'SRATIONAL', 'DOUBLE'].indexOf(fieldTypeName) !== -1) {
            return 8;
          }
          return 0;
        }
        getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset) {
          const fieldValues = [];
          const fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
          const fieldValueSize = fieldTypeLength * typeCount;
          if (fieldValueSize <= 4) {
            if (this._littleEndian === false) fieldValues.push(valueOffset >>> (4 - fieldTypeLength) * 8);else fieldValues.push(valueOffset);
          } else {
            for (let i = 0; i < typeCount; i++) {
              const indexOffset = fieldTypeLength * i;
              if (fieldTypeLength >= 8) {
                if (['RATIONAL', 'SRATIONAL'].indexOf(fieldTypeName) !== -1) {
                  fieldValues.push(this.getUint32(valueOffset + indexOffset));
                  fieldValues.push(this.getUint32(valueOffset + indexOffset + 4));
                } else {
                  logID(8000);
                }
              } else {
                fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
              }
            }
          }
          if (fieldTypeName === 'ASCII') {
            fieldValues.forEach((e, i, a) => {
              a[i] = String.fromCharCode(e);
            });
          }
          return fieldValues;
        }
        getBytes(numBytes, offset) {
          if (numBytes <= 0) {
            logID(8001);
          } else if (numBytes <= 1) {
            return this.getUint8(offset);
          } else if (numBytes <= 2) {
            return this.getUint16(offset);
          } else if (numBytes <= 3) {
            return this.getUint32(offset) >>> 8;
          } else if (numBytes <= 4) {
            return this.getUint32(offset);
          } else {
            logID(8002);
          }
          return 0;
        }
        getBits(numBits, byteOffset, bitOffset) {
          bitOffset = bitOffset || 0;
          const extraBytes = Math.floor(bitOffset / 8);
          const newByteOffset = byteOffset + extraBytes;
          const totalBits = bitOffset + numBits;
          const shiftRight = 32 - numBits;
          let shiftLeft = 0;
          let rawBits = 0;
          if (totalBits <= 0) {
            logID(6023);
          } else if (totalBits <= 8) {
            shiftLeft = 24 + bitOffset;
            rawBits = this.getUint8(newByteOffset);
          } else if (totalBits <= 16) {
            shiftLeft = 16 + bitOffset;
            rawBits = this.getUint16(newByteOffset);
          } else if (totalBits <= 32) {
            shiftLeft = bitOffset;
            rawBits = this.getUint32(newByteOffset);
          } else {
            logID(6022);
          }
          return {
            bits: rawBits << shiftLeft >>> shiftRight,
            byteOffset: newByteOffset + Math.floor(totalBits / 8),
            bitOffset: totalBits % 8
          };
        }
        parseFileDirectory(offset) {
          const numDirEntries = this.getUint16(offset);
          const tiffFields = [];
          let i = 0;
          let entryCount = 0;
          for (i = offset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
            const fieldTag = this.getUint16(i);
            const fieldType = this.getUint16(i + 2);
            const typeCount = this.getUint32(i + 4);
            const valueOffset = this.getUint32(i + 8);
            const fieldTagName = this.getFieldTagName(fieldTag);
            const fieldTypeName = this.getFieldTypeName(fieldType);
            const fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
            tiffFields[fieldTagName] = {
              type: fieldTypeName,
              values: fieldValues
            };
          }
          this._fileDirectories.push(tiffFields);
          const nextIFDByteOffset = this.getUint32(i);
          if (nextIFDByteOffset !== 0x00000000) {
            this.parseFileDirectory(nextIFDByteOffset);
          }
        }
        clampColorSample(colorSample, bitsPerSample) {
          const multiplier = Math.pow(2, 8 - bitsPerSample);
          return Math.floor(colorSample * multiplier + (multiplier - 1));
        }
        parseTIFF(tiffData, canvas) {
          canvas = canvas || ccwindow$1.document.createElement('canvas');
          this._tiffData = tiffData;
          this._canvas = canvas;
          this.checkLittleEndian();
          if (!this.hasTowel()) {
            return;
          }
          const firstIFDByteOffset = this.getUint32(4);
          this._fileDirectories.length = 0;
          this.parseFileDirectory(firstIFDByteOffset);
          const fileDirectory = this._fileDirectories[0];
          const imageWidth = fileDirectory.ImageWidth.values[0];
          const imageLength = fileDirectory.ImageLength.values[0];
          this._canvas.width = imageWidth;
          this._canvas.height = imageLength;
          const strips = [];
          const compression = fileDirectory.Compression ? fileDirectory.Compression.values[0] : 1;
          const samplesPerPixel = fileDirectory.SamplesPerPixel.values[0];
          const sampleProperties = [];
          let bitsPerPixel = 0;
          let hasBytesPerPixel = false;
          fileDirectory.BitsPerSample.values.forEach((bitsPerSample, i, bitsPerSampleValues) => {
            sampleProperties[i] = {
              bitsPerSample,
              hasBytesPerSample: false,
              bytesPerSample: undefined
            };
            if (bitsPerSample % 8 === 0) {
              sampleProperties[i].hasBytesPerSample = true;
              sampleProperties[i].bytesPerSample = bitsPerSample / 8;
            }
            bitsPerPixel += bitsPerSample;
          }, this);
          let bytesPerPixel = 0;
          if (bitsPerPixel % 8 === 0) {
            hasBytesPerPixel = true;
            bytesPerPixel = bitsPerPixel / 8;
          }
          const stripOffsetValues = fileDirectory.StripOffsets.values;
          const numStripOffsetValues = stripOffsetValues.length;
          let stripByteCountValues;
          if (fileDirectory.StripByteCounts) {
            stripByteCountValues = fileDirectory.StripByteCounts.values;
          } else {
            logID(8003);
            if (numStripOffsetValues === 1) {
              stripByteCountValues = [Math.ceil(imageWidth * imageLength * bitsPerPixel / 8)];
            } else {
              throw Error(getError(6024));
            }
          }
          let blockLength = 1;
          let iterations = 1;
          for (let i = 0; i < numStripOffsetValues; i++) {
            const stripOffset = stripOffsetValues[i];
            strips[i] = [];
            const stripByteCount = stripByteCountValues[i];
            for (let byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0; byteOffset < stripByteCount; byteOffset += jIncrement) {
              switch (compression) {
                case 1:
                  pixel = [];
                  for (let m = 0; m < samplesPerPixel; m++) {
                    const s = sampleProperties[m];
                    if (s.hasBytesPerSample) {
                      const sampleOffset = s.bytesPerSample * m;
                      pixel.push(this.getBytes(s.bytesPerSample, stripOffset + byteOffset + sampleOffset));
                    } else {
                      const sampleInfo = this.getBits(s.bitsPerSample, stripOffset + byteOffset, bitOffset);
                      pixel.push(sampleInfo.bits);
                      byteOffset = sampleInfo.byteOffset - stripOffset;
                      bitOffset = sampleInfo.bitOffset;
                      throw RangeError(getError(6025));
                    }
                  }
                  strips[i].push(pixel);
                  if (hasBytesPerPixel) {
                    jIncrement = bytesPerPixel;
                  } else {
                    jIncrement = 0;
                    throw RangeError(getError(6026));
                  }
                  break;
                case 2:
                  break;
                case 3:
                  break;
                case 4:
                  break;
                case 5:
                  break;
                case 6:
                  break;
                case 7:
                  break;
                case 32773:
                  if (getHeader) {
                    getHeader = false;
                    const header = this.getUint8(stripOffset + byteOffset);
                    if (header >= 0 && header <= 127) {
                      blockLength = header + 1;
                    } else if (header >= -127 && header <= -1) {
                      iterations = -header + 1;
                    } else {
                        getHeader = true;
                      }
                  } else {
                    const currentByte = this.getUint8(stripOffset + byteOffset);
                    for (let m = 0; m < iterations; m++) {
                      const s = sampleProperties[sample];
                      if (s.hasBytesPerSample) {
                        currentSample = currentSample << 8 * numBytes | currentByte;
                        numBytes++;
                        if (numBytes === s.bytesPerSample) {
                          pixel.push(currentSample);
                          currentSample = numBytes = 0;
                          sample++;
                        }
                      } else {
                        throw RangeError(getError(6025));
                      }
                      if (sample === samplesPerPixel) {
                        strips[i].push(pixel);
                        pixel = [];
                        sample = 0;
                      }
                    }
                    blockLength--;
                    if (blockLength === 0) {
                      getHeader = true;
                    }
                  }
                  jIncrement = 1;
                  break;
              }
            }
          }
          if (canvas.getContext) {
            const ctx = this._canvas.getContext('2d');
            ctx.fillStyle = 'rgba(255, 255, 255, 0)';
            const rowsPerStrip = fileDirectory.RowsPerStrip ? fileDirectory.RowsPerStrip.values[0] : imageLength;
            const numStrips = strips.length;
            const imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
            const rowsInLastStrip = imageLengthModRowsPerStrip === 0 ? rowsPerStrip : imageLengthModRowsPerStrip;
            let numRowsInStrip = rowsPerStrip;
            let numRowsInPreviousStrip = 0;
            const photometricInterpretation = fileDirectory.PhotometricInterpretation.values[0];
            let extraSamplesValues = [];
            let numExtraSamples = 0;
            if (fileDirectory.ExtraSamples) {
              extraSamplesValues = fileDirectory.ExtraSamples.values;
              numExtraSamples = extraSamplesValues.length;
            }
            let colorMapValues = [];
            let colorMapSampleSize = 0;
            if (fileDirectory.ColorMap) {
              colorMapValues = fileDirectory.ColorMap.values;
              colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
            }
            for (let i = 0; i < numStrips; i++) {
              if (i + 1 === numStrips) {
                numRowsInStrip = rowsInLastStrip;
              }
              const numPixels = strips[i].length;
              const yPadding = numRowsInPreviousStrip * i;
              for (let y = 0, j = 0; y < numRowsInStrip && j < numPixels; y++) {
                for (let x = 0; x < imageWidth; x++, j++) {
                  const pixelSamples = strips[i][j];
                  let red = 0;
                  let green = 0;
                  let blue = 0;
                  let opacity = 1.0;
                  if (numExtraSamples > 0) {
                    for (let k = 0; k < numExtraSamples; k++) {
                      if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
                        opacity = pixelSamples[3 + k] / 256;
                        break;
                      }
                    }
                  }
                  switch (photometricInterpretation) {
                    case 0:
                      let invertValue = 0;
                      if (sampleProperties[0].hasBytesPerSample) {
                        invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
                      }
                      pixelSamples.forEach((sample, index, samples) => {
                        samples[index] = invertValue - sample;
                      });
                    case 1:
                      red = green = blue = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
                      break;
                    case 2:
                      red = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
                      green = this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample);
                      blue = this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample);
                      break;
                    case 3:
                      if (colorMapValues === undefined) {
                        throw Error(getError(6027));
                      }
                      const colorMapIndex = pixelSamples[0];
                      red = this.clampColorSample(colorMapValues[colorMapIndex], 16);
                      green = this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16);
                      blue = this.clampColorSample(colorMapValues[2 * colorMapSampleSize + colorMapIndex], 16);
                      break;
                    default:
                      throw RangeError(getError(6028, photometricInterpretation));
                  }
                  ctx.fillStyle = `rgba(${red}, ${green}, ${blue}, ${opacity})`;
                  ctx.fillRect(x, yPadding + y, 1, 1);
                }
              }
              numRowsInPreviousStrip = numRowsInStrip;
            }
          }
          return this._canvas;
        }
      }
      const fieldTagNames = {
        0x013B: 'Artist',
        0x0102: 'BitsPerSample',
        0x0109: 'CellLength',
        0x0108: 'CellWidth',
        0x0140: 'ColorMap',
        0x0103: 'Compression',
        0x8298: 'Copyright',
        0x0132: 'DateTime',
        0x0152: 'ExtraSamples',
        0x010A: 'FillOrder',
        0x0121: 'FreeByteCounts',
        0x0120: 'FreeOffsets',
        0x0123: 'GrayResponseCurve',
        0x0122: 'GrayResponseUnit',
        0x013C: 'HostComputer',
        0x010E: 'ImageDescription',
        0x0101: 'ImageLength',
        0x0100: 'ImageWidth',
        0x010F: 'Make',
        0x0119: 'MaxSampleValue',
        0x0118: 'MinSampleValue',
        0x0110: 'Model',
        0x00FE: 'NewSubfileType',
        0x0112: 'Orientation',
        0x0106: 'PhotometricInterpretation',
        0x011C: 'PlanarConfiguration',
        0x0128: 'ResolutionUnit',
        0x0116: 'RowsPerStrip',
        0x0115: 'SamplesPerPixel',
        0x0131: 'Software',
        0x0117: 'StripByteCounts',
        0x0111: 'StripOffsets',
        0x00FF: 'SubfileType',
        0x0107: 'Threshholding',
        0x011A: 'XResolution',
        0x011B: 'YResolution',
        0x0146: 'BadFaxLines',
        0x0147: 'CleanFaxData',
        0x0157: 'ClipPath',
        0x0148: 'ConsecutiveBadFaxLines',
        0x01B1: 'Decode',
        0x01B2: 'DefaultImageColor',
        0x010D: 'DocumentName',
        0x0150: 'DotRange',
        0x0141: 'HalftoneHints',
        0x015A: 'Indexed',
        0x015B: 'JPEGTables',
        0x011D: 'PageName',
        0x0129: 'PageNumber',
        0x013D: 'Predictor',
        0x013F: 'PrimaryChromaticities',
        0x0214: 'ReferenceBlackWhite',
        0x0153: 'SampleFormat',
        0x022F: 'StripRowCounts',
        0x014A: 'SubIFDs',
        0x0124: 'T4Options',
        0x0125: 'T6Options',
        0x0145: 'TileByteCounts',
        0x0143: 'TileLength',
        0x0144: 'TileOffsets',
        0x0142: 'TileWidth',
        0x012D: 'TransferFunction',
        0x013E: 'WhitePoint',
        0x0158: 'XClipPathUnits',
        0x011E: 'XPosition',
        0x0211: 'YCbCrCoefficients',
        0x0213: 'YCbCrPositioning',
        0x0212: 'YCbCrSubSampling',
        0x0159: 'YClipPathUnits',
        0x011F: 'YPosition',
        0x9202: 'ApertureValue',
        0xA001: 'ColorSpace',
        0x9004: 'DateTimeDigitized',
        0x9003: 'DateTimeOriginal',
        0x8769: 'Exif IFD',
        0x9000: 'ExifVersion',
        0x829A: 'ExposureTime',
        0xA300: 'FileSource',
        0x9209: 'Flash',
        0xA000: 'FlashpixVersion',
        0x829D: 'FNumber',
        0xA420: 'ImageUniqueID',
        0x9208: 'LightSource',
        0x927C: 'MakerNote',
        0x9201: 'ShutterSpeedValue',
        0x9286: 'UserComment',
        0x83BB: 'IPTC',
        0x8773: 'ICC Profile',
        0x02BC: 'XMP',
        0xA480: 'GDAL_METADATA',
        0xA481: 'GDAL_NODATA',
        0x8649: 'Photoshop'
      };
      const fieldTypeNames = {
        0x0001: 'BYTE',
        0x0002: 'ASCII',
        0x0003: 'SHORT',
        0x0004: 'LONG',
        0x0005: 'RATIONAL',
        0x0006: 'SBYTE',
        0x0007: 'UNDEFINED',
        0x0008: 'SSHORT',
        0x0009: 'SLONG',
        0x000A: 'SRATIONAL',
        0x000B: 'FLOAT',
        0x000C: 'DOUBLE'
      };

      const BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      const BASE64_VALUES = new Array(123);
      for (let i = 0; i < 123; ++i) {
        BASE64_VALUES[i] = 64;
      }
      for (let i = 0; i < 64; ++i) {
        BASE64_VALUES[BASE64_KEYS.charCodeAt(i)] = i;
      }

      var Base64 = {
        name: 'Jacob__Codec__Base64'
      };
      Base64.decode = function Jacob__Codec__Base64__decode(input) {
        var output = [],
          chr1,
          chr2,
          chr3,
          enc1,
          enc2,
          enc3,
          enc4,
          i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
          enc1 = BASE64_VALUES[input.charCodeAt(i++)];
          enc2 = BASE64_VALUES[input.charCodeAt(i++)];
          enc3 = BASE64_VALUES[input.charCodeAt(i++)];
          enc4 = BASE64_VALUES[input.charCodeAt(i++)];
          chr1 = enc1 << 2 | enc2 >> 4;
          chr2 = (enc2 & 15) << 4 | enc3 >> 2;
          chr3 = (enc3 & 3) << 6 | enc4;
          output.push(String.fromCharCode(chr1));
          if (enc3 !== 64) {
            output.push(String.fromCharCode(chr2));
          }
          if (enc4 !== 64) {
            output.push(String.fromCharCode(chr3));
          }
        }
        output = output.join('');
        return output;
      };
      Base64.decodeAsArray = function Jacob__Codec__Base64___decodeAsArray(input, bytes) {
        var dec = this.decode(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };

      var GZip = function Jacob__GZip(data) {
        this.data = data;
        this.debug = false;
        this.gpflags = undefined;
        this.files = 0;
        this.unzipped = [];
        this.buf32k = new Array(32768);
        this.bIdx = 0;
        this.modeZIP = false;
        this.bytepos = 0;
        this.bb = 1;
        this.bits = 0;
        this.nameBuf = [];
        this.fileout = undefined;
        this.literalTree = new Array(GZip.LITERALS);
        this.distanceTree = new Array(32);
        this.treepos = 0;
        this.Places = null;
        this.len = 0;
        this.fpos = new Array(17);
        this.fpos[0] = 0;
        this.flens = undefined;
        this.fmax = undefined;
      };
      GZip.gunzip = function (string) {
        if (string.constructor === Array) ; else if (string.constructor === String) ;
        var gzip = new GZip(string);
        return gzip.gunzip()[0][0];
      };
      GZip.HufNode = function () {
        this.b0 = 0;
        this.b1 = 0;
        this.jump = null;
        this.jumppos = -1;
      };
      GZip.LITERALS = 288;
      GZip.NAMEMAX = 256;
      GZip.bitReverse = [0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff];
      GZip.cplens = [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, 0, 0];
      GZip.cplext = [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, 99, 99];
      GZip.cpdist = [0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0009, 0x000d, 0x0011, 0x0019, 0x0021, 0x0031, 0x0041, 0x0061, 0x0081, 0x00c1, 0x0101, 0x0181, 0x0201, 0x0301, 0x0401, 0x0601, 0x0801, 0x0c01, 0x1001, 0x1801, 0x2001, 0x3001, 0x4001, 0x6001];
      GZip.cpdext = [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];
      GZip.border = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
      GZip.prototype.gunzip = function () {
        this.outputArr = [];
        this.nextFile();
        return this.unzipped;
      };
      GZip.prototype.readByte = function () {
        this.bits += 8;
        if (this.bytepos < this.data.length) {
          return this.data.charCodeAt(this.bytepos++);
        } else {
          return -1;
        }
      };
      GZip.prototype.byteAlign = function () {
        this.bb = 1;
      };
      GZip.prototype.readBit = function () {
        var carry;
        this.bits++;
        carry = this.bb & 1;
        this.bb >>= 1;
        if (this.bb === 0) {
          this.bb = this.readByte();
          carry = this.bb & 1;
          this.bb = this.bb >> 1 | 0x80;
        }
        return carry;
      };
      GZip.prototype.readBits = function (a) {
        var res = 0,
          i = a;
        while (i--) res = res << 1 | this.readBit();
        if (a) res = GZip.bitReverse[res] >> 8 - a;
        return res;
      };
      GZip.prototype.flushBuffer = function () {
        this.bIdx = 0;
      };
      GZip.prototype.addBuffer = function (a) {
        this.buf32k[this.bIdx++] = a;
        this.outputArr.push(String.fromCharCode(a));
        if (this.bIdx === 0x8000) this.bIdx = 0;
      };
      GZip.prototype.IsPat = function () {
        while (1) {
          if (this.fpos[this.len] >= this.fmax) return -1;
          if (this.flens[this.fpos[this.len]] === this.len) return this.fpos[this.len]++;
          this.fpos[this.len]++;
        }
      };
      GZip.prototype.Rec = function () {
        var curplace = this.Places[this.treepos];
        var tmp;
        if (this.len === 17) {
          return -1;
        }
        this.treepos++;
        this.len++;
        tmp = this.IsPat();
        if (tmp >= 0) {
          curplace.b0 = tmp;
        } else {
          curplace.b0 = 0x8000;
          if (this.Rec()) return -1;
        }
        tmp = this.IsPat();
        if (tmp >= 0) {
          curplace.b1 = tmp;
          curplace.jump = null;
        } else {
          curplace.b1 = 0x8000;
          curplace.jump = this.Places[this.treepos];
          curplace.jumppos = this.treepos;
          if (this.Rec()) return -1;
        }
        this.len--;
        return 0;
      };
      GZip.prototype.CreateTree = function (currentTree, numval, lengths, show) {
        var i;
        this.Places = currentTree;
        this.treepos = 0;
        this.flens = lengths;
        this.fmax = numval;
        for (i = 0; i < 17; i++) this.fpos[i] = 0;
        this.len = 0;
        if (this.Rec()) {
          return -1;
        }
        return 0;
      };
      GZip.prototype.DecodeValue = function (currentTree) {
        var len,
          i,
          xtreepos = 0,
          X = currentTree[xtreepos],
          b;
        while (1) {
          b = this.readBit();
          if (b) {
            if (!(X.b1 & 0x8000)) {
              return X.b1;
            }
            X = X.jump;
            len = currentTree.length;
            for (i = 0; i < len; i++) {
              if (currentTree[i] === X) {
                xtreepos = i;
                break;
              }
            }
          } else {
            if (!(X.b0 & 0x8000)) {
              return X.b0;
            }
            xtreepos++;
            X = currentTree[xtreepos];
          }
        }
        return -1;
      };
      GZip.prototype.DeflateLoop = function () {
        var last, c, type, i, len;
        do {
          last = this.readBit();
          type = this.readBits(2);
          if (type === 0) {
            var blockLen, cSum;
            this.byteAlign();
            blockLen = this.readByte();
            blockLen |= this.readByte() << 8;
            cSum = this.readByte();
            cSum |= this.readByte() << 8;
            if ((blockLen ^ ~cSum) & 0xffff) {
              document.write("BlockLen checksum mismatch\n");
            }
            while (blockLen--) {
              c = this.readByte();
              this.addBuffer(c);
            }
          } else if (type === 1) {
            var j;
            while (1) {
              j = GZip.bitReverse[this.readBits(7)] >> 1;
              if (j > 23) {
                j = j << 1 | this.readBit();
                if (j > 199) {
                  j -= 128;
                  j = j << 1 | this.readBit();
                } else {
                  j -= 48;
                  if (j > 143) {
                    j = j + 136;
                  }
                }
              } else {
                j += 256;
              }
              if (j < 256) {
                this.addBuffer(j);
              } else if (j === 256) {
                break;
              } else {
                var len, dist;
                j -= 256 + 1;
                len = this.readBits(GZip.cplext[j]) + GZip.cplens[j];
                j = GZip.bitReverse[this.readBits(5)] >> 3;
                if (GZip.cpdext[j] > 8) {
                  dist = this.readBits(8);
                  dist |= this.readBits(GZip.cpdext[j] - 8) << 8;
                } else {
                  dist = this.readBits(GZip.cpdext[j]);
                }
                dist += GZip.cpdist[j];
                for (j = 0; j < len; j++) {
                  var c = this.buf32k[this.bIdx - dist & 0x7fff];
                  this.addBuffer(c);
                }
              }
            }
          } else if (type === 2) {
            var j, n, literalCodes, distCodes, lenCodes;
            var ll = new Array(288 + 32);
            literalCodes = 257 + this.readBits(5);
            distCodes = 1 + this.readBits(5);
            lenCodes = 4 + this.readBits(4);
            for (j = 0; j < 19; j++) {
              ll[j] = 0;
            }
            for (j = 0; j < lenCodes; j++) {
              ll[GZip.border[j]] = this.readBits(3);
            }
            len = this.distanceTree.length;
            for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode();
            if (this.CreateTree(this.distanceTree, 19, ll, 0)) {
              this.flushBuffer();
              return 1;
            }
            n = literalCodes + distCodes;
            i = 0;
            while (i < n) {
              j = this.DecodeValue(this.distanceTree);
              if (j < 16) {
                ll[i++] = j;
              } else if (j === 16) {
                var l;
                j = 3 + this.readBits(2);
                if (i + j > n) {
                  this.flushBuffer();
                  return 1;
                }
                l = i ? ll[i - 1] : 0;
                while (j--) {
                  ll[i++] = l;
                }
              } else {
                if (j === 17) {
                  j = 3 + this.readBits(3);
                } else {
                  j = 11 + this.readBits(7);
                }
                if (i + j > n) {
                  this.flushBuffer();
                  return 1;
                }
                while (j--) {
                  ll[i++] = 0;
                }
              }
            }
            len = this.literalTree.length;
            for (i = 0; i < len; i++) this.literalTree[i] = new GZip.HufNode();
            if (this.CreateTree(this.literalTree, literalCodes, ll, 0)) {
              this.flushBuffer();
              return 1;
            }
            len = this.literalTree.length;
            for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode();
            var ll2 = new Array();
            for (i = literalCodes; i < ll.length; i++) ll2[i - literalCodes] = ll[i];
            if (this.CreateTree(this.distanceTree, distCodes, ll2, 0)) {
              this.flushBuffer();
              return 1;
            }
            while (1) {
              j = this.DecodeValue(this.literalTree);
              if (j >= 256) {
                var len, dist;
                j -= 256;
                if (j === 0) {
                  break;
                }
                j--;
                len = this.readBits(GZip.cplext[j]) + GZip.cplens[j];
                j = this.DecodeValue(this.distanceTree);
                if (GZip.cpdext[j] > 8) {
                  dist = this.readBits(8);
                  dist |= this.readBits(GZip.cpdext[j] - 8) << 8;
                } else {
                  dist = this.readBits(GZip.cpdext[j]);
                }
                dist += GZip.cpdist[j];
                while (len--) {
                  var c = this.buf32k[this.bIdx - dist & 0x7fff];
                  this.addBuffer(c);
                }
              } else {
                this.addBuffer(j);
              }
            }
          }
        } while (!last);
        this.flushBuffer();
        this.byteAlign();
        return 0;
      };
      GZip.prototype.unzipFile = function (name) {
        var i;
        this.gunzip();
        for (i = 0; i < this.unzipped.length; i++) {
          if (this.unzipped[i][1] === name) {
            return this.unzipped[i][0];
          }
        }
      };
      GZip.prototype.nextFile = function () {
        this.outputArr = [];
        this.modeZIP = false;
        var tmp = [];
        tmp[0] = this.readByte();
        tmp[1] = this.readByte();
        if (tmp[0] === 0x78 && tmp[1] === 0xda) {
          this.DeflateLoop();
          this.unzipped[this.files] = [this.outputArr.join(''), "geonext.gxt"];
          this.files++;
        }
        if (tmp[0] === 0x1f && tmp[1] === 0x8b) {
          this.skipdir();
          this.unzipped[this.files] = [this.outputArr.join(''), "file"];
          this.files++;
        }
        if (tmp[0] === 0x50 && tmp[1] === 0x4b) {
          this.modeZIP = true;
          tmp[2] = this.readByte();
          tmp[3] = this.readByte();
          if (tmp[2] === 0x03 && tmp[3] === 0x04) {
            tmp[0] = this.readByte();
            tmp[1] = this.readByte();
            this.gpflags = this.readByte();
            this.gpflags |= this.readByte() << 8;
            var method = this.readByte();
            method |= this.readByte() << 8;
            this.readByte();
            this.readByte();
            this.readByte();
            this.readByte();
            var compSize = this.readByte();
            compSize |= this.readByte() << 8;
            compSize |= this.readByte() << 16;
            compSize |= this.readByte() << 24;
            var size = this.readByte();
            size |= this.readByte() << 8;
            size |= this.readByte() << 16;
            size |= this.readByte() << 24;
            var filelen = this.readByte();
            filelen |= this.readByte() << 8;
            var extralen = this.readByte();
            extralen |= this.readByte() << 8;
            i = 0;
            this.nameBuf = [];
            while (filelen--) {
              var c = this.readByte();
              if (c === "/" | c === ":") {
                i = 0;
              } else if (i < GZip.NAMEMAX - 1) {
                this.nameBuf[i++] = String.fromCharCode(c);
              }
            }
            if (!this.fileout) this.fileout = this.nameBuf;
            var i = 0;
            while (i < extralen) {
              c = this.readByte();
              i++;
            }
            if (method === 8) {
              this.DeflateLoop();
              this.unzipped[this.files] = [this.outputArr.join(''), this.nameBuf.join('')];
              this.files++;
            }
            this.skipdir();
          }
        }
      };
      GZip.prototype.skipdir = function () {
        var tmp = [];
        var compSize, size, i, c;
        if (this.gpflags & 8) {
          tmp[0] = this.readByte();
          tmp[1] = this.readByte();
          tmp[2] = this.readByte();
          tmp[3] = this.readByte();
          compSize = this.readByte();
          compSize |= this.readByte() << 8;
          compSize |= this.readByte() << 16;
          compSize |= this.readByte() << 24;
          size = this.readByte();
          size |= this.readByte() << 8;
          size |= this.readByte() << 16;
          size |= this.readByte() << 24;
        }
        if (this.modeZIP) this.nextFile();
        tmp[0] = this.readByte();
        if (tmp[0] !== 8) {
          return 0;
        }
        this.gpflags = this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        if (this.gpflags & 4) {
          tmp[0] = this.readByte();
          tmp[2] = this.readByte();
          this.len = tmp[0] + 256 * tmp[1];
          for (i = 0; i < this.len; i++) this.readByte();
        }
        if (this.gpflags & 8) {
          i = 0;
          this.nameBuf = [];
          while (c = this.readByte()) {
            if (c === "7" || c === ":") i = 0;
            if (i < GZip.NAMEMAX - 1) this.nameBuf[i++] = c;
          }
        }
        if (this.gpflags & 16) {
          while (c = this.readByte()) {}
        }
        if (this.gpflags & 2) {
          this.readByte();
          this.readByte();
        }
        this.DeflateLoop();
        size = this.readByte();
        size |= this.readByte() << 8;
        size |= this.readByte() << 16;
        size |= this.readByte() << 24;
        if (this.modeZIP) this.nextFile();
      };

      var codec = {
        name: 'Jacob__Codec'
      };
      codec.Base64 = Base64;
      codec.GZip = GZip;
      codec.unzip = function () {
        return codec.GZip.gunzip.apply(codec.GZip, arguments);
      };
      codec.unzipBase64 = function () {
        var buffer = codec.Base64.decode.apply(codec.Base64, arguments);
        try {
          return codec.GZip.gunzip.call(codec.GZip, buffer);
        } catch (e) {
          return buffer.slice(7);
        }
      };
      codec.unzipBase64AsArray = function (input, bytes) {
        bytes = bytes || 1;
        var dec = this.unzipBase64(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };
      codec.unzipAsArray = function (input, bytes) {
        bytes = bytes || 1;
        var dec = this.unzip(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };

      var _dec$M, _dec2$I, _dec3$C, _dec4$s, _dec5$r, _dec6$k, _class$L, _class2$H, _initializer$G, _initializer2$C, _initializer3$u, _initializer4$r, _initializer5$m, _initializer6$i, _initializer7$e, _initializer8$d, _initializer9$b, _initializer10$a, _initializer11$a, _initializer12$9, _initializer13$6, _initializer14$5, _initializer15$4, _initializer16$4, _initializer17$2, _initializer18$2, _initializer19$1, _initializer20$1, _initializer21$1, _initializer22, _initializer23, _initializer24, _initializer25, _initializer26, _initializer27, _initializer28, _initializer29, _initializer30, _initializer31, _initializer32, _initializer33, _initializer34, _initializer35, _initializer36, _initializer37, _initializer38, _initializer39, _initializer40, _initializer41, _initializer42, _initializer43, _class3$h;
      function getImageFormatByData(imgData) {
        if (imgData.length > 8 && imgData[0] === 0x89 && imgData[1] === 0x50 && imgData[2] === 0x4E && imgData[3] === 0x47 && imgData[4] === 0x0D && imgData[5] === 0x0A && imgData[6] === 0x1A && imgData[7] === 0x0A) {
          return 1;
        }
        if (imgData.length > 2 && (imgData[0] === 0x49 && imgData[1] === 0x49 || imgData[0] === 0x4d && imgData[1] === 0x4d || imgData[0] === 0xff && imgData[1] === 0xd8)) {
          return 2;
        }
        return 10;
      }
      function getParticleComponents(node) {
        const parent = node.parent;
        const comp = node.getComponent(ParticleSystem2D);
        if (!parent || !comp) {
          return node.getComponentsInChildren(ParticleSystem2D);
        }
        return getParticleComponents(parent);
      }
      let ParticleSystem2D = exports("ParticleSystem2D", (_dec$M = ccclass$H('cc.ParticleSystem2D'), _dec2$I = type$a(ParticleAsset), _dec3$C = type$a(SpriteFrame), _dec4$s = type$a(PositionType), _dec5$r = type$a(EmitterMode), _dec6$k = formerlySerializedAs$2('preview'), _dec$M(_class$L = (_class2$H = (_class3$h = class ParticleSystem2D extends UIRenderer {
        get custom() {
          return this._custom;
        }
        set custom(value) {
          if (this._custom !== value) {
            this._custom = value;
            this._applyFile();
            this._updateMaterial();
          }
        }
        get file() {
          return this._file;
        }
        set file(value) {
          if (this._file !== value) {
            this._file = value;
            if (value) {
              this._applyFile();
            } else {
              this.custom = true;
            }
          }
        }
        get spriteFrame() {
          return this._spriteFrame;
        }
        set spriteFrame(value) {
          const lastSprite = this._renderSpriteFrame;
          if (lastSprite === value) {
            return;
          }
          this._renderSpriteFrame = value;
          if (!value || value._uuid) {
            this._spriteFrame = value;
          }
          this._applySpriteFrame();
        }
        get particleCount() {
          return this._simulator.particles.length;
        }
        get totalParticles() {
          return this._totalParticles;
        }
        set totalParticles(value) {
          if (this._totalParticles === value) return;
          this._totalParticles = value;
        }
        get startColor() {
          return this._startColor;
        }
        set startColor(val) {
          this._startColor.r = val.r;
          this._startColor.g = val.g;
          this._startColor.b = val.b;
          this._startColor.a = val.a;
        }
        get startColorVar() {
          return this._startColorVar;
        }
        set startColorVar(val) {
          this._startColorVar.r = val.r;
          this._startColorVar.g = val.g;
          this._startColorVar.b = val.b;
          this._startColorVar.a = val.a;
        }
        set color(value) {}
        get color() {
          return this._color;
        }
        get endColor() {
          return this._endColor;
        }
        set endColor(val) {
          this._endColor.r = val.r;
          this._endColor.g = val.g;
          this._endColor.b = val.b;
          this._endColor.a = val.a;
        }
        get endColorVar() {
          return this._endColorVar;
        }
        set endColorVar(val) {
          this._endColorVar.r = val.r;
          this._endColorVar.g = val.g;
          this._endColorVar.b = val.b;
          this._endColorVar.a = val.a;
        }
        get positionType() {
          return this._positionType;
        }
        set positionType(val) {
          this._positionType = val;
          this._updateMaterial();
          this._updatePositionType();
        }
        get preview() {
          return this._preview;
        }
        set preview(val) {
          if (val) {
            this._startPreview();
          } else {
            this._stopPreview();
          }
          this._preview = val;
        }
        get stopped() {
          return this._stopped;
        }
        get active() {
          return this._simulator.active;
        }
        get assembler() {
          return this._assembler;
        }
        constructor() {
          super();
          this.duration = _initializer$G && _initializer$G();
          this.emissionRate = _initializer2$C && _initializer2$C();
          this.life = _initializer3$u && _initializer3$u();
          this.lifeVar = _initializer4$r && _initializer4$r();
          this.angle = _initializer5$m && _initializer5$m();
          this.angleVar = _initializer6$i && _initializer6$i();
          this.startSize = _initializer7$e && _initializer7$e();
          this.startSizeVar = _initializer8$d && _initializer8$d();
          this.endSize = _initializer9$b && _initializer9$b();
          this.endSizeVar = _initializer10$a && _initializer10$a();
          this.startSpin = _initializer11$a && _initializer11$a();
          this.startSpinVar = _initializer12$9 && _initializer12$9();
          this.endSpin = _initializer13$6 && _initializer13$6();
          this.endSpinVar = _initializer14$5 && _initializer14$5();
          this.sourcePos = _initializer15$4 && _initializer15$4();
          this.posVar = _initializer16$4 && _initializer16$4();
          this.emitterMode = _initializer17$2 && _initializer17$2();
          this.gravity = _initializer18$2 && _initializer18$2();
          this.speed = _initializer19$1 && _initializer19$1();
          this.speedVar = _initializer20$1 && _initializer20$1();
          this.tangentialAccel = _initializer21$1 && _initializer21$1();
          this.tangentialAccelVar = _initializer22 && _initializer22();
          this.radialAccel = _initializer23 && _initializer23();
          this.radialAccelVar = _initializer24 && _initializer24();
          this.rotationIsDir = _initializer25 && _initializer25();
          this.startRadius = _initializer26 && _initializer26();
          this.startRadiusVar = _initializer27 && _initializer27();
          this.endRadius = _initializer28 && _initializer28();
          this.endRadiusVar = _initializer29 && _initializer29();
          this.rotatePerS = _initializer30 && _initializer30();
          this.rotatePerSVar = _initializer31 && _initializer31();
          this.aspectRatio = 1;
          this.playOnLoad = _initializer32 && _initializer32();
          this.autoRemoveOnFinish = _initializer33 && _initializer33();
          this._preview = _initializer34 && _initializer34();
          this._custom = _initializer35 && _initializer35();
          this._file = _initializer36 && _initializer36();
          this._spriteFrame = _initializer37 && _initializer37();
          this._totalParticles = _initializer38 && _initializer38();
          this._startColor = _initializer39 && _initializer39();
          this._startColorVar = _initializer40 && _initializer40();
          this._endColor = _initializer41 && _initializer41();
          this._endColorVar = _initializer42 && _initializer42();
          this._positionType = _initializer43 && _initializer43();
          this._stopped = true;
          this._useFile = void 0;
          this.initProperties();
          this._useFile = false;
        }
        onEnable() {
          super.onEnable();
          this._updateMaterial();
          this._updatePositionType();
        }
        onDestroy() {
          super.onDestroy();
          if (this.autoRemoveOnFinish) {
            this.autoRemoveOnFinish = false;
          }
          this._simulator.uvFilled = 0;
          if (this._simulator.renderData && this._assembler) {
            this._assembler.removeData(this._simulator.renderData);
          }
        }
        initProperties() {
          this._previewTimer = null;
          this._focused = false;
          this.aspectRatio = 1;
          this._simulator = new Simulator(this);
        }
        onFocusInEditor() {
          this._focused = true;
          const components = getParticleComponents(this.node);
          for (let i = 0; i < components.length; ++i) {
            components[i]._startPreview();
          }
        }
        onLostFocusInEditor() {
          this._focused = false;
          const components = getParticleComponents(this.node);
          for (let i = 0; i < components.length; ++i) {
            components[i]._stopPreview();
          }
        }
        _startPreview() {
          if (this._preview) {
            this.resetSystem();
          }
        }
        _stopPreview() {
          if (this._preview) {
            this.resetSystem();
            this.stopSystem();
          }
          if (this._previewTimer) {
            clearInterval(this._previewTimer);
          }
        }
        __preload() {
          super.__preload();
          if (this._custom && this.spriteFrame && !this._renderSpriteFrame) {
            this._applySpriteFrame();
          } else if (this._file) {
            if (this._custom) {
              const missCustomTexture = !this._getTexture();
              if (missCustomTexture) {
                this._applyFile();
              }
            } else {
              this._applyFile();
            }
          }
          {
            if (this.playOnLoad) {
              this.resetSystem();
            }
          }
        }
        _flushAssembler() {
          const assembler = ParticleSystem2D.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._assembler && this._assembler.createData) {
            this._simulator.renderData = this._assembler.createData(this);
            this._simulator.renderData.particleInitRenderDrawInfo(this.renderEntity);
            this._simulator.initDrawInfo();
          }
        }
        lateUpdate(dt) {
          if (!this._simulator.finished) {
            this._simulator.step(dt);
          }
        }
        addParticle() {}
        stopSystem() {
          this._stopped = true;
          this._simulator.stop();
        }
        resetSystem() {
          this._stopped = false;
          this._simulator.reset();
          this.markForUpdateRenderData();
        }
        isFull() {
          return this.particleCount >= this.totalParticles;
        }
        _applyFile() {
          const file = this._file;
          if (file) {
            if (!file) {
              errorID(6029);
              return;
            }
            if (!this.isValid) {
              return;
            }
            this._plistFile = file.nativeUrl;
            if (!this._custom) {
              const isDiffFrame = this._spriteFrame !== file.spriteFrame;
              if (isDiffFrame) this.spriteFrame = file.spriteFrame;
              this._initWithDictionary(file._nativeAsset);
            }
            if (!this._spriteFrame) {
              if (file.spriteFrame) {
                this.spriteFrame = file.spriteFrame;
              } else if (this._custom) {
                this._initTextureWithDictionary(file._nativeAsset);
              }
            } else if (!this._renderSpriteFrame && this._spriteFrame) {
              this._applySpriteFrame();
            }
          }
        }
        _initTextureWithDictionary(dict) {
          if (dict.spriteFrameUuid) {
            const spriteFrameUuid = dict.spriteFrameUuid;
            assetManager.loadAny(spriteFrameUuid, (err, spriteFrame) => {
              if (err) {
                dict.spriteFrameUuid = undefined;
                this._initTextureWithDictionary(dict);
                error(err);
              } else {
                this.spriteFrame = spriteFrame;
              }
            });
          } else {
            const imgPath = changeBasename(this._plistFile, dict.textureFileName || '');
            if (dict.textureFileName) {
              assetManager.loadRemote(imgPath, (err, imageAsset) => {
                if (err) {
                  dict.textureFileName = undefined;
                  this._initTextureWithDictionary(dict);
                  error(err);
                } else {
                  if (imageAsset) {
                    this.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                  } else {
                    this.spriteFrame = SpriteFrame.createWithImage(builtinResMgr.get('white-texture'));
                  }
                }
              });
            } else if (dict.textureImageData) {
              const textureData = dict.textureImageData;
              if (textureData && textureData.length > 0) {
                let imgPathName = imgPath;
                if (this.file) {
                  imgPathName += `-${this.file.uuid}`;
                }
                let imageAsset = assetManager.assets.get(imgPathName);
                if (!imageAsset) {
                  const buffer = codec.unzipBase64AsArray(textureData, 1);
                  if (!buffer) {
                    warnID(6030, this._file.name);
                    return false;
                  }
                  const imageFormat = getImageFormatByData(buffer);
                  if (imageFormat !== 2 && imageFormat !== 1) {
                    warnID(6031, this._file.name);
                    return false;
                  }
                  const canvasObj = ccwindow$1.document.createElement('canvas');
                  if (imageFormat === 1) {
                    const myPngObj = new PNGReader(buffer);
                    myPngObj.render(canvasObj);
                  } else {
                    if (!this._tiffReader) {
                      this._tiffReader = new TiffReader();
                    }
                    this._tiffReader.parseTIFF(buffer, canvasObj);
                  }
                  imageAsset = new ImageAsset$1(canvasObj);
                  assetManager.assets.add(imgPathName, imageAsset);
                }
                if (!imageAsset) {
                  warnID(6032, this._file.name);
                }
                if (imageAsset) {
                  this.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                } else {
                  this.spriteFrame = SpriteFrame.createWithImage(builtinResMgr.get('white-texture'));
                }
              } else {
                return false;
              }
            }
          }
          return true;
        }
        _initWithDictionary(dict) {
          this._useFile = true;
          this.totalParticles = parseInt(dict.maxParticles || 0);
          this.life = parseFloat(dict.particleLifespan || 0);
          this.lifeVar = parseFloat(dict.particleLifespanVariance || 0);
          const _tempEmissionRate = dict.emissionRate;
          if (_tempEmissionRate) {
            this.emissionRate = _tempEmissionRate;
          } else {
            this.emissionRate = Math.min(this.totalParticles / this.life, Number.MAX_VALUE);
          }
          this.duration = parseFloat(dict.duration || 0);
          this._srcBlendFactor = parseInt(dict.blendFuncSource || 2);
          this._dstBlendFactor = parseInt(dict.blendFuncDestination || 4);
          const locStartColor = this._startColor;
          locStartColor.r = parseFloat(dict.startColorRed || 0) * 255;
          locStartColor.g = parseFloat(dict.startColorGreen || 0) * 255;
          locStartColor.b = parseFloat(dict.startColorBlue || 0) * 255;
          locStartColor.a = parseFloat(dict.startColorAlpha || 0) * 255;
          const locStartColorVar = this._startColorVar;
          locStartColorVar.r = parseFloat(dict.startColorVarianceRed || 0) * 255;
          locStartColorVar.g = parseFloat(dict.startColorVarianceGreen || 0) * 255;
          locStartColorVar.b = parseFloat(dict.startColorVarianceBlue || 0) * 255;
          locStartColorVar.a = parseFloat(dict.startColorVarianceAlpha || 0) * 255;
          const locEndColor = this._endColor;
          locEndColor.r = parseFloat(dict.finishColorRed || 0) * 255;
          locEndColor.g = parseFloat(dict.finishColorGreen || 0) * 255;
          locEndColor.b = parseFloat(dict.finishColorBlue || 0) * 255;
          locEndColor.a = parseFloat(dict.finishColorAlpha || 0) * 255;
          const locEndColorVar = this._endColorVar;
          locEndColorVar.r = parseFloat(dict.finishColorVarianceRed || 0) * 255;
          locEndColorVar.g = parseFloat(dict.finishColorVarianceGreen || 0) * 255;
          locEndColorVar.b = parseFloat(dict.finishColorVarianceBlue || 0) * 255;
          locEndColorVar.a = parseFloat(dict.finishColorVarianceAlpha || 0) * 255;
          this.startSize = parseFloat(dict.startParticleSize || 0);
          this.startSizeVar = parseFloat(dict.startParticleSizeVariance || 0);
          this.endSize = parseFloat(dict.finishParticleSize || 0);
          this.endSizeVar = parseFloat(dict.finishParticleSizeVariance || 0);
          this.positionType = parseFloat(dict.positionType !== undefined ? dict.positionType : PositionType.FREE);
          this.sourcePos.set(0, 0);
          this.posVar.set(parseFloat(dict.sourcePositionVariancex || 0), parseFloat(dict.sourcePositionVariancey || 0));
          this.angle = parseFloat(dict.angle || 0);
          this.angleVar = parseFloat(dict.angleVariance || 0);
          this.startSpin = parseFloat(dict.rotationStart || 0);
          this.startSpinVar = parseFloat(dict.rotationStartVariance || 0);
          this.endSpin = parseFloat(dict.rotationEnd || 0);
          this.endSpinVar = parseFloat(dict.rotationEndVariance || 0);
          this.emitterMode = parseInt(dict.emitterType || EmitterMode.GRAVITY);
          if (this.emitterMode === EmitterMode.GRAVITY) {
            this.gravity.set(parseFloat(dict.gravityx || 0), parseFloat(dict.gravityy || 0));
            this.speed = parseFloat(dict.speed || 0);
            this.speedVar = parseFloat(dict.speedVariance || 0);
            this.radialAccel = parseFloat(dict.radialAcceleration || 0);
            this.radialAccelVar = parseFloat(dict.radialAccelVariance || 0);
            this.tangentialAccel = parseFloat(dict.tangentialAcceleration || 0);
            this.tangentialAccelVar = parseFloat(dict.tangentialAccelVariance || 0);
            let locRotationIsDir = dict.rotationIsDir || '';
            if (locRotationIsDir !== null) {
              locRotationIsDir = locRotationIsDir.toString().toLowerCase();
              this.rotationIsDir = locRotationIsDir === 'true' || locRotationIsDir === '1';
            } else {
              this.rotationIsDir = false;
            }
          } else if (this.emitterMode === EmitterMode.RADIUS) {
            this.startRadius = parseFloat(dict.maxRadius || 0);
            this.startRadiusVar = parseFloat(dict.maxRadiusVariance || 0);
            this.endRadius = parseFloat(dict.minRadius || 0);
            this.endRadiusVar = parseFloat(dict.minRadiusVariance || 0);
            this.rotatePerS = parseFloat(dict.rotatePerSecond || 0);
            this.rotatePerSVar = parseFloat(dict.rotatePerSecondVariance || 0);
          } else {
            warnID(6009);
            return false;
          }
          this._initTextureWithDictionary(dict);
          return true;
        }
        _syncAspect() {
          if (this._renderSpriteFrame) {
            const frameRect = this._renderSpriteFrame.rect;
            this.aspectRatio = frameRect.width / frameRect.height;
          }
        }
        _applySpriteFrame() {
          this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame;
          if (this._renderSpriteFrame) {
            if (this._renderSpriteFrame.texture) {
              if (this._simulator) {
                this._simulator.updateUVs(true);
              }
              this._syncAspect();
              this._updateMaterial();
              this._stopped = false;
              this.markForUpdateRenderData();
            }
          } else {
            this.resetSystem();
          }
        }
        _getTexture() {
          return this._renderSpriteFrame && this._renderSpriteFrame.texture;
        }
        _updateMaterial() {
          if (this._customMaterial) {
            this.setSharedMaterial(this._customMaterial, 0);
            const target = this.getRenderMaterial(0).passes[0].blendState.targets[0];
            this._dstBlendFactor = target.blendDst;
            this._srcBlendFactor = target.blendSrc;
          }
          const mat = this.getMaterialInstance(0);
          if (mat) mat.recompileShaders({
            USE_LOCAL: this._positionType !== PositionType.FREE
          });
          if (mat && mat.passes.length > 0) {
            this._updateBlendFunc();
          }
        }
        _finishedSimulation() {
          this.resetSystem();
          this.stopSystem();
          this.markForUpdateRenderData();
          if (this.autoRemoveOnFinish && this._stopped) {
            this.node.destroy();
          }
        }
        _canRender() {
          return super._canRender() && !this._stopped && this._renderSpriteFrame !== null && this._renderSpriteFrame !== undefined;
        }
        _render(render) {
          if (this._positionType === PositionType.RELATIVE) {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, this.node.parent);
          } else if (this.positionType === PositionType.GROUPED) {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, this.node);
          } else {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, null);
          }
        }
        _updatePositionType() {
          if (this._positionType === PositionType.RELATIVE) {
            this._renderEntity.setRenderTransform(this.node.parent);
            this._renderEntity.setUseLocal(true);
          } else if (this.positionType === PositionType.GROUPED) {
            this._renderEntity.setRenderTransform(this.node);
            this._renderEntity.setUseLocal(true);
          } else {
            this._renderEntity.setRenderTransform(null);
            this._renderEntity.setUseLocal(false);
          }
        }
      }, _class3$h.EmitterMode = EmitterMode, _class3$h.PositionType = PositionType, _class3$h.DURATION_INFINITY = DURATION_INFINITY, _class3$h.START_SIZE_EQUAL_TO_END_SIZE = START_SIZE_EQUAL_TO_END_SIZE, _class3$h.START_RADIUS_EQUAL_TO_END_RADIUS = START_RADIUS_EQUAL_TO_END_RADIUS, _class3$h), (_applyDecoratedDescriptor(_class2$H.prototype, "file", [_dec2$I], Object.getOwnPropertyDescriptor(_class2$H.prototype, "file"), _class2$H.prototype), _applyDecoratedDescriptor(_class2$H.prototype, "spriteFrame", [_dec3$C], Object.getOwnPropertyDescriptor(_class2$H.prototype, "spriteFrame"), _class2$H.prototype), _initializer$G = applyDecoratedInitializer(_class2$H.prototype, "duration", [serializable$l], function () {
        return -1;
      }), _initializer2$C = applyDecoratedInitializer(_class2$H.prototype, "emissionRate", [serializable$l], function () {
        return 10;
      }), _initializer3$u = applyDecoratedInitializer(_class2$H.prototype, "life", [serializable$l], function () {
        return 1;
      }), _initializer4$r = applyDecoratedInitializer(_class2$H.prototype, "lifeVar", [serializable$l], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$H.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$H.prototype, "color"), _class2$H.prototype), _initializer5$m = applyDecoratedInitializer(_class2$H.prototype, "angle", [serializable$l], function () {
        return 90;
      }), _initializer6$i = applyDecoratedInitializer(_class2$H.prototype, "angleVar", [serializable$l], function () {
        return 20;
      }), _initializer7$e = applyDecoratedInitializer(_class2$H.prototype, "startSize", [serializable$l], function () {
        return 50;
      }), _initializer8$d = applyDecoratedInitializer(_class2$H.prototype, "startSizeVar", [serializable$l], function () {
        return 0;
      }), _initializer9$b = applyDecoratedInitializer(_class2$H.prototype, "endSize", [serializable$l], function () {
        return 0;
      }), _initializer10$a = applyDecoratedInitializer(_class2$H.prototype, "endSizeVar", [serializable$l], function () {
        return 0;
      }), _initializer11$a = applyDecoratedInitializer(_class2$H.prototype, "startSpin", [serializable$l], function () {
        return 0;
      }), _initializer12$9 = applyDecoratedInitializer(_class2$H.prototype, "startSpinVar", [serializable$l], function () {
        return 0;
      }), _initializer13$6 = applyDecoratedInitializer(_class2$H.prototype, "endSpin", [serializable$l], function () {
        return 0;
      }), _initializer14$5 = applyDecoratedInitializer(_class2$H.prototype, "endSpinVar", [serializable$l], function () {
        return 0;
      }), _initializer15$4 = applyDecoratedInitializer(_class2$H.prototype, "sourcePos", [serializable$l], function () {
        return Vec2.ZERO.clone();
      }), _initializer16$4 = applyDecoratedInitializer(_class2$H.prototype, "posVar", [serializable$l], function () {
        return Vec2.ZERO.clone();
      }), _applyDecoratedDescriptor(_class2$H.prototype, "positionType", [_dec4$s], Object.getOwnPropertyDescriptor(_class2$H.prototype, "positionType"), _class2$H.prototype), _initializer17$2 = applyDecoratedInitializer(_class2$H.prototype, "emitterMode", [serializable$l, _dec5$r], function () {
        return EmitterMode.GRAVITY;
      }), _initializer18$2 = applyDecoratedInitializer(_class2$H.prototype, "gravity", [serializable$l], function () {
        return Vec2.ZERO.clone();
      }), _initializer19$1 = applyDecoratedInitializer(_class2$H.prototype, "speed", [serializable$l], function () {
        return 180;
      }), _initializer20$1 = applyDecoratedInitializer(_class2$H.prototype, "speedVar", [serializable$l], function () {
        return 50;
      }), _initializer21$1 = applyDecoratedInitializer(_class2$H.prototype, "tangentialAccel", [serializable$l], function () {
        return 80;
      }), _initializer22 = applyDecoratedInitializer(_class2$H.prototype, "tangentialAccelVar", [serializable$l], function () {
        return 0;
      }), _initializer23 = applyDecoratedInitializer(_class2$H.prototype, "radialAccel", [serializable$l], function () {
        return 0;
      }), _initializer24 = applyDecoratedInitializer(_class2$H.prototype, "radialAccelVar", [serializable$l], function () {
        return 0;
      }), _initializer25 = applyDecoratedInitializer(_class2$H.prototype, "rotationIsDir", [serializable$l], function () {
        return false;
      }), _initializer26 = applyDecoratedInitializer(_class2$H.prototype, "startRadius", [serializable$l], function () {
        return 0;
      }), _initializer27 = applyDecoratedInitializer(_class2$H.prototype, "startRadiusVar", [serializable$l], function () {
        return 0;
      }), _initializer28 = applyDecoratedInitializer(_class2$H.prototype, "endRadius", [serializable$l], function () {
        return 0;
      }), _initializer29 = applyDecoratedInitializer(_class2$H.prototype, "endRadiusVar", [serializable$l], function () {
        return 0;
      }), _initializer30 = applyDecoratedInitializer(_class2$H.prototype, "rotatePerS", [serializable$l], function () {
        return 0;
      }), _initializer31 = applyDecoratedInitializer(_class2$H.prototype, "rotatePerSVar", [serializable$l], function () {
        return 0;
      }), _initializer32 = applyDecoratedInitializer(_class2$H.prototype, "playOnLoad", [serializable$l], function () {
        return true;
      }), _initializer33 = applyDecoratedInitializer(_class2$H.prototype, "autoRemoveOnFinish", [serializable$l], function () {
        return false;
      }), _initializer34 = applyDecoratedInitializer(_class2$H.prototype, "_preview", [_dec6$k], function () {
        return true;
      }), _initializer35 = applyDecoratedInitializer(_class2$H.prototype, "_custom", [serializable$l], function () {
        return false;
      }), _initializer36 = applyDecoratedInitializer(_class2$H.prototype, "_file", [serializable$l], function () {
        return null;
      }), _initializer37 = applyDecoratedInitializer(_class2$H.prototype, "_spriteFrame", [serializable$l], function () {
        return null;
      }), _initializer38 = applyDecoratedInitializer(_class2$H.prototype, "_totalParticles", [serializable$l], function () {
        return 150;
      }), _initializer39 = applyDecoratedInitializer(_class2$H.prototype, "_startColor", [serializable$l], function () {
        return new Color$1(255, 255, 255, 255);
      }), _initializer40 = applyDecoratedInitializer(_class2$H.prototype, "_startColorVar", [serializable$l], function () {
        return new Color$1(0, 0, 0, 0);
      }), _initializer41 = applyDecoratedInitializer(_class2$H.prototype, "_endColor", [serializable$l], function () {
        return new Color$1(255, 255, 255, 0);
      }), _initializer42 = applyDecoratedInitializer(_class2$H.prototype, "_endColorVar", [serializable$l], function () {
        return new Color$1(0, 0, 0, 0);
      }), _initializer43 = applyDecoratedInitializer(_class2$H.prototype, "_positionType", [serializable$l], function () {
        return PositionType.FREE;
      })), _class2$H)) || _class$L));

      var _dec$L, _dec2$H, _class2$G, _class3$g, _initializer$F, _initializer2$B, _initializer3$t, _initializer4$q, _initializer5$l, _initializer6$h, _class4$4;
      class Point {
        constructor(point, dir) {
          this.point = new Vec2();
          this.dir = new Vec2();
          this.distance = 0;
          this.time = 0;
          if (point) this.point.set(point);
          if (dir) this.dir.set(dir);
        }
        setPoint(x, y) {
          this.point.x = x;
          this.point.y = y;
        }
        setDir(x, y) {
          this.dir.x = x;
          this.dir.y = y;
        }
      }
      let MotionStreak = exports("MotionStreak", (_dec$L = ccclass$H('cc.MotionStreak'), _dec2$H = type$a(Texture2D$1), _dec$L(_class2$G = (_class3$g = (_class4$4 = class MotionStreak extends UIRenderer {
        constructor() {
          super();
          this._preview = _initializer$F && _initializer$F();
          this._fadeTime = _initializer2$B && _initializer2$B();
          this._minSeg = _initializer3$t && _initializer3$t();
          this._stroke = _initializer4$q && _initializer4$q();
          this._texture = _initializer5$l && _initializer5$l();
          this._fastMode = _initializer6$h && _initializer6$h();
          this._points = [];
        }
        get preview() {
          return this._preview;
        }
        set preview(val) {
          this._preview = val;
          this.reset();
        }
        get fadeTime() {
          return this._fadeTime;
        }
        set fadeTime(val) {
          this._fadeTime = val;
          this.reset();
        }
        get minSeg() {
          return this._minSeg;
        }
        set minSeg(val) {
          this._minSeg = val;
        }
        get stroke() {
          return this._stroke;
        }
        set stroke(val) {
          this._stroke = val;
        }
        get texture() {
          return this._texture;
        }
        set texture(val) {
          if (this._texture === val) return;
          this._texture = val;
        }
        get fastMode() {
          return this._fastMode;
        }
        set fastMode(val) {
          this._fastMode = val;
        }
        get points() {
          return this._points;
        }
        onEnable() {
          super.onEnable();
          this.reset();
        }
        _flushAssembler() {
          const assembler = MotionStreak.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (!this._renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this._renderData.material = this.material;
              this._updateColor();
            }
          }
        }
        onFocusInEditor() {
          if (this._preview) {
            this.reset();
          }
        }
        onLostFocusInEditor() {
          if (this._preview) {
            this.reset();
          }
        }
        reset() {
          this._points.length = 0;
          if (this._renderData) this._renderData.clear();
        }
        lateUpdate(dt) {
          if (this._assembler) this._assembler.update(this, dt);
        }
        _render(render) {
          render.commitComp(this, this._renderData, this._texture, this._assembler, null);
        }
      }, _class4$4.Point = Point, _class4$4), (_applyDecoratedDescriptor(_class3$g.prototype, "texture", [_dec2$H], Object.getOwnPropertyDescriptor(_class3$g.prototype, "texture"), _class3$g.prototype), _initializer$F = applyDecoratedInitializer(_class3$g.prototype, "_preview", [serializable$l], function () {
        return false;
      }), _initializer2$B = applyDecoratedInitializer(_class3$g.prototype, "_fadeTime", [serializable$l], function () {
        return 1;
      }), _initializer3$t = applyDecoratedInitializer(_class3$g.prototype, "_minSeg", [serializable$l], function () {
        return 1;
      }), _initializer4$q = applyDecoratedInitializer(_class3$g.prototype, "_stroke", [serializable$l], function () {
        return 64;
      }), _initializer5$l = applyDecoratedInitializer(_class3$g.prototype, "_texture", [serializable$l], function () {
        return null;
      }), _initializer6$h = applyDecoratedInitializer(_class3$g.prototype, "_fastMode", [serializable$l], function () {
        return false;
      })), _class3$g)) || _class2$G));

      new Vec2();
      const _normal = new Vec2();
      const _vec2 = new Vec2();
      let QUAD_INDICES;
      function normal(out, dir) {
        out.x = -dir.y;
        out.y = dir.x;
        return out;
      }
      const MotionStreakAssembler = {
        createData(comp) {
          const renderData = comp.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(16, (16 - 2) * 3);
          return renderData;
        },
        update(comp, dt) {
          const stroke = comp.stroke / 2;
          const node = comp.node;
          const matrix = node.worldMatrix;
          const tx = matrix.m12;
          const ty = matrix.m13;
          const points = comp.points;
          let cur;
          if (points.length > 1) {
            const point = points[0];
            const difx = point.point.x - tx;
            const dify = point.point.y - ty;
            if (difx * difx + dify * dify < comp.minSeg) {
              cur = point;
            }
          }
          if (!cur) {
            cur = new MotionStreak.Point();
            points.unshift(cur);
          }
          cur.setPoint(tx, ty);
          cur.time = comp.fadeTime + dt;
          let vertexCount = 0;
          let indexCount = 0;
          if (points.length < 2) {
            return;
          }
          const renderData = comp.renderData;
          this.updateRenderDataCache(comp, renderData);
          const color = comp.color;
          const cr = color.r;
          const cg = color.g;
          const cb = color.b;
          const ca = color.a;
          const prev = points[1];
          prev.distance = Vec2.subtract(_vec2, cur.point, prev.point).length();
          _vec2.normalize();
          prev.setDir(_vec2.x, _vec2.y);
          cur.setDir(_vec2.x, _vec2.y);
          renderData.dataLength = points.length * 2;
          const data = renderData.data;
          const fadeTime = comp.fadeTime;
          let findLast = false;
          for (let i = points.length - 1; i >= 0; i--) {
            const p = points[i];
            const point = p.point;
            const dir = p.dir;
            p.time -= dt;
            if (p.time < 0) {
              points.splice(i, 1);
              continue;
            }
            const progress = p.time / fadeTime;
            const next = points[i - 1];
            if (!findLast) {
              if (!next) {
                points.splice(i, 1);
                continue;
              }
              point.x = next.point.x - dir.x * progress;
              point.y = next.point.y - dir.y * progress;
            }
            findLast = true;
            normal(_normal, dir);
            const da = progress * ca;
            let offset = vertexCount;
            data[offset].x = point.x + _normal.x * stroke;
            data[offset].y = point.y + _normal.y * stroke;
            data[offset].u = 1;
            data[offset].v = progress;
            data[offset].color.set(cr, cg, cb, da);
            offset += 1;
            data[offset].x = point.x - _normal.x * stroke;
            data[offset].y = point.y - _normal.y * stroke;
            data[offset].u = 0;
            data[offset].v = progress;
            data[offset].color.set(cr, cg, cb, da);
            vertexCount += 2;
          }
          indexCount = vertexCount <= 2 ? 0 : (vertexCount - 2) * 3;
          renderData.resize(vertexCount, indexCount);
          {
            const indexCount = renderData.indexCount;
            this.createQuadIndices(comp, indexCount);
            renderData.chunk.setIndexBuffer(QUAD_INDICES);
            this.updateWorldVertexAllData(comp);
            renderData.updateRenderData(comp, comp.texture);
            comp.markForUpdateRenderData();
          }
        },
        updateWorldVertexAllData(comp) {
          const renderData = comp.renderData;
          const stride = renderData.floatStride;
          const dataList = renderData.data;
          const vData = renderData.chunk.vb;
          for (let i = 0; i < dataList.length; i++) {
            const offset = i * stride;
            vData[offset + 0] = dataList[i].x;
            vData[offset + 1] = dataList[i].y;
            vData[offset + 2] = dataList[i].z;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
            Color$1.toArray(vData, dataList[i].color, offset + 5);
          }
        },
        createQuadIndices(comp, indexCount) {
          const renderData = comp.renderData;
          const chunk = renderData.chunk;
          const vid = 0;
          const meshBuffer = chunk.meshBuffer;
          let indexOffset = meshBuffer.indexOffset;
          QUAD_INDICES = null;
          QUAD_INDICES = new Uint16Array(indexCount);
          for (let i = 0, l = indexCount; i < l; i += 2) {
            const start = vid + i;
            QUAD_INDICES[indexOffset++] = start;
            QUAD_INDICES[indexOffset++] = start + 2;
            QUAD_INDICES[indexOffset++] = start + 1;
            QUAD_INDICES[indexOffset++] = start + 1;
            QUAD_INDICES[indexOffset++] = start + 2;
            QUAD_INDICES[indexOffset++] = start + 3;
          }
        },
        updateRenderDataCache(comp, renderData) {
          if (renderData.passDirty) {
            renderData.updatePass(comp);
          }
          if (renderData.nodeDirty) {
            renderData.updateNode(comp);
          }
          if (renderData.textureDirty && comp.texture) {
            renderData.updateTexture(comp.texture);
            renderData.material = comp.getRenderMaterial(0);
          }
          if (renderData.hashDirty) {
            renderData.updateHash();
          }
        },
        updateRenderData(comp) {
          {
            comp.renderData.renderDrawInfo.setVertDirty(false);
            comp.node.hasChangedFlags = 0;
          }
        },
        updateColor(comp) {},
        fillBuffers(comp, renderer) {
          const renderData = comp.renderData;
          const chunk = renderData.chunk;
          const dataList = renderData.data;
          const vertexCount = renderData.vertexCount;
          const indexCount = renderData.indexCount;
          const vData = chunk.vb;
          let vertexOffset = 0;
          for (let i = 0; i < vertexCount; i++) {
            const vert = dataList[i];
            vData[vertexOffset++] = vert.x;
            vData[vertexOffset++] = vert.y;
            vData[vertexOffset++] = vert.z;
            vData[vertexOffset++] = vert.u;
            vData[vertexOffset++] = vert.v;
            Color$1.toArray(vData, vert.color, vertexOffset);
            vertexOffset += 4;
          }
          chunk.bufferId;
          const vid = chunk.vertexOffset;
          const meshBuffer = chunk.meshBuffer;
          const ib = chunk.meshBuffer.iData;
          let indexOffset = meshBuffer.indexOffset;
          for (let i = 0, l = indexCount; i < l; i += 2) {
            const start = vid + i;
            ib[indexOffset++] = start;
            ib[indexOffset++] = start + 2;
            ib[indexOffset++] = start + 1;
            ib[indexOffset++] = start + 1;
            ib[indexOffset++] = start + 2;
            ib[indexOffset++] = start + 3;
          }
          meshBuffer.indexOffset += renderData.indexCount;
          meshBuffer.setDirty();
        }
      };
      const MotionStreakAssemblerManager = exports("MotionStreakAssemblerManager", {
        getAssembler(comp) {
          return MotionStreakAssembler;
        }
      });
      MotionStreak.Assembler = MotionStreakAssemblerManager;

      const ParticleAssembler = {
        maxParticleDeltaTime: 0,
        createData(comp) {
          return MeshRenderData.add();
        },
        removeData(data) {
          MeshRenderData.remove(data);
        },
        updateRenderData() {},
        fillBuffers(comp, renderer) {}
      };
      const ParticleSystem2DAssembler = exports("ParticleSystem2DAssembler", {
        getAssembler(comp) {
          if (!ParticleAssembler.maxParticleDeltaTime) {
            ParticleAssembler.maxParticleDeltaTime = cclegacy.game.frameTime / 1000 * 2;
          }
          return ParticleAssembler;
        }
      });
      ParticleSystem2D.Assembler = ParticleSystem2DAssembler;

      function register(id, wrapper) {
        log(`[PHYSICS2D]: register ${id}.`);
        selector.backend[id] = wrapper;
        if (!selector.physicsWorld || selector.id === id) {
          const mutableSelector = selector;
          mutableSelector.id = id;
          mutableSelector.wrapper = wrapper;
        }
      }
      function switchTo(id) {
        const mutableSelector = selector;
        if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
          log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
          mutableSelector.id = id;
          mutableSelector.wrapper = selector.backend[id];
          mutableSelector.physicsWorld = createPhysicsWorld();
        } else {
          log(`[PHYSICS2D]: using ${mutableSelector.id}.`);
          mutableSelector.physicsWorld = createPhysicsWorld();
        }
      }
      const selector = exports("selector", {
        id: '',
        switchTo,
        register,
        wrapper: {},
        backend: {},
        physicsWorld: null,
        runInEditor: !EDITOR
      });
      const FUNC = (...v) => 0;
      const ENTIRE_WORLD = {
        impl: null,
        debugDrawFlags: 0,
        setGravity: FUNC,
        setAllowSleep: FUNC,
        step: FUNC,
        syncPhysicsToScene: FUNC,
        syncSceneToPhysics: FUNC,
        raycast: FUNC,
        testPoint: FUNC,
        testAABB: FUNC,
        drawDebug: FUNC
      };
      function checkPhysicsModule(obj) {
        if (obj == null) {
          errorID(9600);
          return true;
        }
        return false;
      }
      function createPhysicsWorld() {
        if (checkPhysicsModule(selector.wrapper.PhysicsWorld)) {
          return ENTIRE_WORLD;
        }
        return new selector.wrapper.PhysicsWorld();
      }
      const EntireBody = {
        impl: null,
        rigidBody: null,
        isAwake: false,
        isSleeping: false,
        initialize: FUNC,
        setType: FUNC,
        setLinearDamping: FUNC,
        setAngularDamping: FUNC,
        setGravityScale: FUNC,
        setFixedRotation: FUNC,
        setAllowSleep: FUNC,
        isActive: FUNC,
        setActive: FUNC,
        wakeUp: FUNC,
        sleep: FUNC,
        getMass: FUNC,
        getInertia: FUNC,
        getLinearVelocity: FUNC,
        setLinearVelocity: FUNC,
        getLinearVelocityFromWorldPoint: FUNC,
        getAngularVelocity: FUNC,
        setAngularVelocity: FUNC,
        getLocalVector: FUNC,
        getWorldVector: FUNC,
        getLocalPoint: FUNC,
        getWorldPoint: FUNC,
        getLocalCenter: FUNC,
        getWorldCenter: FUNC,
        applyForce: FUNC,
        applyForceToCenter: FUNC,
        applyTorque: FUNC,
        applyLinearImpulse: FUNC,
        applyLinearImpulseToCenter: FUNC,
        applyAngularImpulse: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC
      };
      function createRigidBody() {
        const PHYSICS_2D_BUILTIN = selector.id === 'builtin';
        if (PHYSICS_2D_BUILTIN) {
          return EntireBody;
        } else {
          if (checkPhysicsModule(selector.wrapper.RigidBody)) {
            return EntireBody;
          }
          return new selector.wrapper.RigidBody();
        }
      }
      const CREATE_COLLIDER_PROXY = {
        INITED: false
      };
      const ENTIRE_SHAPE = {
        impl: null,
        collider: null,
        worldAABB: null,
        worldPoints: null,
        worldPosition: null,
        worldRadius: null,
        initialize: FUNC,
        apply: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        onGroupChanged: 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[1] = function createBoxShape() {
          if (checkPhysicsModule(selector.wrapper.BoxShape)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.BoxShape();
        };
        CREATE_COLLIDER_PROXY[2] = function createCircleShape() {
          if (checkPhysicsModule(selector.wrapper.CircleShape)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.CircleShape();
        };
        CREATE_COLLIDER_PROXY[3] = function createPolygonShape() {
          if (checkPhysicsModule(selector.wrapper.PolygonShape)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.PolygonShape();
        };
      }
      const CREATE_JOINT_PROXY = {
        INITED: false
      };
      const ENTIRE_JOINT = {
        impl: null,
        initialize: FUNC,
        apply: FUNC,
        setDampingRatio: FUNC,
        setFrequency: FUNC,
        setMaxForce: FUNC,
        setTarget: FUNC,
        setDistance: FUNC,
        setAngularOffset: FUNC,
        setCorrectionFactor: FUNC,
        setLinearOffset: FUNC,
        setMaxLength: FUNC,
        setMaxTorque: FUNC,
        setLowerLimit: FUNC,
        setUpperLimit: FUNC,
        setMaxMotorForce: FUNC,
        setMaxMotorTorque: FUNC,
        setMotorSpeed: FUNC,
        enableLimit: FUNC,
        enableMotor: FUNC,
        setLowerAngle: FUNC,
        setUpperAngle: FUNC
      };
      function createJoint(type) {
        initJointProxy();
        return CREATE_JOINT_PROXY[type]();
      }
      function initJointProxy() {
        if (CREATE_JOINT_PROXY.INITED) return;
        CREATE_JOINT_PROXY.INITED = true;
        const PHYSICS_2D_BUILTIN = selector.id === 'builtin';
        CREATE_JOINT_PROXY[2] = function createSpringJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.SpringJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.SpringJoint();
          }
        };
        CREATE_JOINT_PROXY[1] = function createDistanceJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.DistanceJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.DistanceJoint();
          }
        };
        CREATE_JOINT_PROXY[5] = function createFixedJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.FixedJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.FixedJoint();
          }
        };
        CREATE_JOINT_PROXY[4] = function createMouseJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.MouseJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.MouseJoint();
          }
        };
        CREATE_JOINT_PROXY[7] = function createRelativeJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.RelativeJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.RelativeJoint();
          }
        };
        CREATE_JOINT_PROXY[6] = function createSliderJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.SliderJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.SliderJoint();
          }
        };
        CREATE_JOINT_PROXY[3] = function createWheelJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.WheelJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.WheelJoint();
          }
        };
        CREATE_JOINT_PROXY[8] = function createHingeJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector.wrapper.HingeJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector.wrapper.HingeJoint();
          }
        };
      }

      var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

      function getDefaultExportFromCjs (x) {
      	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
      }

      var box2d_umd = {exports: {}};

      (function(module,exports){(function(global,factory){factory(exports);})(commonjsGlobal,function(exports){function b2Assert(condition,...args){if(!condition){throw new Error(...args);}}function b2Maybe(value,def){return value!==undefined?value:def;}const b2_maxFloat=1E+37;const b2_epsilon=1E-5;const b2_epsilon_sq=b2_epsilon*b2_epsilon;const b2_pi=3.14159265359;const b2_maxManifoldPoints=2;const b2_maxPolygonVertices=8;const b2_aabbExtension=0.1;const b2_aabbMultiplier=2;const b2_linearSlop=0.008;const b2_angularSlop=2/180*b2_pi;const b2_polygonRadius=2*b2_linearSlop;const b2_maxSubSteps=8;const b2_maxTOIContacts=32;const b2_velocityThreshold=1;const b2_maxLinearCorrection=0.2;const b2_maxAngularCorrection=8/180*b2_pi;const b2_maxTranslation=2;const b2_maxTranslationSquared=b2_maxTranslation*b2_maxTranslation;const b2_maxRotation=0.5*b2_pi;const b2_maxRotationSquared=b2_maxRotation*b2_maxRotation;const b2_baumgarte=0.2;const b2_toiBaumgarte=0.75;const b2_invalidParticleIndex=-1;const b2_maxParticleIndex=0x7FFFFFFF;const b2_particleStride=0.75;const b2_minParticleWeight=1.0;const b2_maxParticlePressure=0.25;const b2_maxParticleForce=0.5;const b2_maxTriadDistance=2.0;const b2_maxTriadDistanceSquared=b2_maxTriadDistance*b2_maxTriadDistance;const b2_minParticleSystemBufferCapacity=256;const b2_barrierCollisionTime=2.5;const b2_timeToSleep=0.5;const b2_linearSleepTolerance=0.01;const b2_angularSleepTolerance=2/180*b2_pi;function b2Alloc(size){return null;}function b2Free(mem){}function b2Log(message,...args){}class b2Version{constructor(major=0,minor=0,revision=0){this.major=0;this.minor=0;this.revision=0;this.major=major;this.minor=minor;this.revision=revision;}toString(){return this.major+"."+this.minor+"."+this.revision;}}const b2_version=new b2Version(2,3,2);const b2_branch="master";const b2_commit="fbf51801d80fc389d43dc46524520e89043b6faf";function b2ParseInt(v){return parseInt(v,10);}function b2ParseUInt(v){return Math.abs(parseInt(v,10));}function b2MakeArray(length,init){const a=new Array(length);for(let i=0;i<length;++i){a[i]=init(i);}return a;}function b2MakeNullArray(length){const a=new Array(length);for(let i=0;i<length;++i){a[i]=null;}return a;}function b2MakeNumberArray(length,init=0){const a=new Array(length);for(let i=0;i<length;++i){a[i]=init;}return a;}const b2_pi_over_180=b2_pi/180;const b2_180_over_pi=180/b2_pi;const b2_two_pi=2*b2_pi;const b2Abs=Math.abs;function b2Min(a,b){return a<b?a:b;}function b2Max(a,b){return a>b?a:b;}function b2Clamp(a,lo,hi){return a<lo?lo:a>hi?hi:a;}function b2Swap(a,b){const tmp=a[0];a[0]=b[0];b[0]=tmp;}const b2IsValid=isFinite;function b2Sq(n){return n*n;}function b2InvSqrt(n){return 1/Math.sqrt(n);}const b2Sqrt=Math.sqrt;const b2Pow=Math.pow;function b2DegToRad(degrees){return degrees*b2_pi_over_180;}function b2RadToDeg(radians){return radians*b2_180_over_pi;}const b2Cos=Math.cos;const b2Sin=Math.sin;const b2Acos=Math.acos;const b2Asin=Math.asin;const b2Atan2=Math.atan2;function b2NextPowerOfTwo(x){x|=x>>1&0x7FFFFFFF;x|=x>>2&0x3FFFFFFF;x|=x>>4&0x0FFFFFFF;x|=x>>8&0x00FFFFFF;x|=x>>16&0x0000FFFF;return x+1;}function b2IsPowerOfTwo(x){return x>0&&(x&x-1)===0;}function b2Random(){return Math.random()*2-1;}function b2RandomRange(lo,hi){return (hi-lo)*Math.random()+lo;}class b2Vec2{constructor(...args){if(args[0]instanceof Float32Array){if(args[0].length!==2){throw new Error();}this.data=args[0];}else {const x=typeof args[0]==="number"?args[0]:0;const y=typeof args[1]==="number"?args[1]:0;this.data=new Float32Array([x,y]);}}get x(){return this.data[0];}set x(value){this.data[0]=value;}get y(){return this.data[1];}set y(value){this.data[1]=value;}Clone(){return new b2Vec2(this.x,this.y);}SetZero(){this.x=0;this.y=0;return this;}Set(x,y){this.x=x;this.y=y;return this;}Copy(other){this.x=other.x;this.y=other.y;return this;}SelfAdd(v){this.x+=v.x;this.y+=v.y;return this;}SelfAddXY(x,y){this.x+=x;this.y+=y;return this;}SelfSub(v){this.x-=v.x;this.y-=v.y;return this;}SelfSubXY(x,y){this.x-=x;this.y-=y;return this;}SelfMul(s){this.x*=s;this.y*=s;return this;}SelfMulAdd(s,v){this.x+=s*v.x;this.y+=s*v.y;return this;}SelfMulSub(s,v){this.x-=s*v.x;this.y-=s*v.y;return this;}Dot(v){return this.x*v.x+this.y*v.y;}Cross(v){return this.x*v.y-this.y*v.x;}Length(){const x=this.x,y=this.y;return Math.sqrt(x*x+y*y);}LengthSquared(){const x=this.x,y=this.y;return x*x+y*y;}Normalize(){const length=this.Length();if(length>=b2_epsilon){const inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return length;}SelfNormalize(){const length=this.Length();if(length>=b2_epsilon){const inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return this;}SelfRotate(radians){const c=Math.cos(radians);const s=Math.sin(radians);const x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;}SelfRotateCosSin(c,s){const x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;}IsValid(){return isFinite(this.x)&&isFinite(this.y);}SelfCrossVS(s){const x=this.x;this.x=s*this.y;this.y=-s*x;return this;}SelfCrossSV(s){const x=this.x;this.x=-s*this.y;this.y=s*x;return this;}SelfMinV(v){this.x=b2Min(this.x,v.x);this.y=b2Min(this.y,v.y);return this;}SelfMaxV(v){this.x=b2Max(this.x,v.x);this.y=b2Max(this.y,v.y);return this;}SelfAbs(){this.x=b2Abs(this.x);this.y=b2Abs(this.y);return this;}SelfNeg(){this.x=-this.x;this.y=-this.y;return this;}SelfSkew(){const x=this.x;this.x=-this.y;this.y=x;return this;}static MakeArray(length){return b2MakeArray(length,i=>new b2Vec2());}static AbsV(v,out){out.x=b2Abs(v.x);out.y=b2Abs(v.y);return out;}static MinV(a,b,out){out.x=b2Min(a.x,b.x);out.y=b2Min(a.y,b.y);return out;}static MaxV(a,b,out){out.x=b2Max(a.x,b.x);out.y=b2Max(a.y,b.y);return out;}static ClampV(v,lo,hi,out){out.x=b2Clamp(v.x,lo.x,hi.x);out.y=b2Clamp(v.y,lo.y,hi.y);return out;}static RotateV(v,radians,out){const v_x=v.x,v_y=v.y;const c=Math.cos(radians);const s=Math.sin(radians);out.x=c*v_x-s*v_y;out.y=s*v_x+c*v_y;return out;}static DotVV(a,b){return a.x*b.x+a.y*b.y;}static CrossVV(a,b){return a.x*b.y-a.y*b.x;}static CrossVS(v,s,out){const v_x=v.x;out.x=s*v.y;out.y=-s*v_x;return out;}static CrossVOne(v,out){const v_x=v.x;out.x=v.y;out.y=-v_x;return out;}static CrossSV(s,v,out){const v_x=v.x;out.x=-s*v.y;out.y=s*v_x;return out;}static CrossOneV(v,out){const v_x=v.x;out.x=-v.y;out.y=v_x;return out;}static AddVV(a,b,out){out.x=a.x+b.x;out.y=a.y+b.y;return out;}static SubVV(a,b,out){out.x=a.x-b.x;out.y=a.y-b.y;return out;}static MulSV(s,v,out){out.x=v.x*s;out.y=v.y*s;return out;}static MulVS(v,s,out){out.x=v.x*s;out.y=v.y*s;return out;}static AddVMulSV(a,s,b,out){out.x=a.x+s*b.x;out.y=a.y+s*b.y;return out;}static SubVMulSV(a,s,b,out){out.x=a.x-s*b.x;out.y=a.y-s*b.y;return out;}static AddVCrossSV(a,s,v,out){const v_x=v.x;out.x=a.x-s*v.y;out.y=a.y+s*v_x;return out;}static MidVV(a,b,out){out.x=(a.x+b.x)*0.5;out.y=(a.y+b.y)*0.5;return out;}static ExtVV(a,b,out){out.x=(b.x-a.x)*0.5;out.y=(b.y-a.y)*0.5;return out;}static IsEqualToV(a,b){return a.x===b.x&&a.y===b.y;}static DistanceVV(a,b){const c_x=a.x-b.x;const c_y=a.y-b.y;return Math.sqrt(c_x*c_x+c_y*c_y);}static DistanceSquaredVV(a,b){const c_x=a.x-b.x;const c_y=a.y-b.y;return c_x*c_x+c_y*c_y;}static NegV(v,out){out.x=-v.x;out.y=-v.y;return out;}}b2Vec2.ZERO=new b2Vec2(0,0);b2Vec2.UNITX=new b2Vec2(1,0);b2Vec2.UNITY=new b2Vec2(0,1);b2Vec2.s_t0=new b2Vec2();b2Vec2.s_t1=new b2Vec2();b2Vec2.s_t2=new b2Vec2();b2Vec2.s_t3=new b2Vec2();const b2Vec2_zero=new b2Vec2(0,0);class b2Vec3{constructor(...args){if(args[0]instanceof Float32Array){if(args[0].length!==3){throw new Error();}this.data=args[0];}else {const x=typeof args[0]==="number"?args[0]:0;const y=typeof args[1]==="number"?args[1]:0;const z=typeof args[2]==="number"?args[2]:0;this.data=new Float32Array([x,y,z]);}}get x(){return this.data[0];}set x(value){this.data[0]=value;}get y(){return this.data[1];}set y(value){this.data[1]=value;}get z(){return this.data[2];}set z(value){this.data[2]=value;}Clone(){return new b2Vec3(this.x,this.y,this.z);}SetZero(){this.x=0;this.y=0;this.z=0;return this;}SetXYZ(x,y,z){this.x=x;this.y=y;this.z=z;return this;}Copy(other){this.x=other.x;this.y=other.y;this.z=other.z;return this;}SelfNeg(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;}SelfAdd(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this;}SelfAddXYZ(x,y,z){this.x+=x;this.y+=y;this.z+=z;return this;}SelfSub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this;}SelfSubXYZ(x,y,z){this.x-=x;this.y-=y;this.z-=z;return this;}SelfMul(s){this.x*=s;this.y*=s;this.z*=s;return this;}static DotV3V3(a,b){return a.x*b.x+a.y*b.y+a.z*b.z;}static CrossV3V3(a,b,out){const a_x=a.x,a_y=a.y,a_z=a.z;const b_x=b.x,b_y=b.y,b_z=b.z;out.x=a_y*b_z-a_z*b_y;out.y=a_z*b_x-a_x*b_z;out.z=a_x*b_y-a_y*b_x;return out;}}b2Vec3.ZERO=new b2Vec3(0,0,0);b2Vec3.s_t0=new b2Vec3();class b2Mat22{constructor(){this.data=new Float32Array([1,0,0,1]);this.ex=new b2Vec2(this.data.subarray(0,2));this.ey=new b2Vec2(this.data.subarray(2,4));}Clone(){return new b2Mat22().Copy(this);}static FromVV(c1,c2){return new b2Mat22().SetVV(c1,c2);}static FromSSSS(r1c1,r1c2,r2c1,r2c2){return new b2Mat22().SetSSSS(r1c1,r1c2,r2c1,r2c2);}static FromAngle(radians){return new b2Mat22().SetAngle(radians);}SetSSSS(r1c1,r1c2,r2c1,r2c2){this.ex.Set(r1c1,r2c1);this.ey.Set(r1c2,r2c2);return this;}SetVV(c1,c2){this.ex.Copy(c1);this.ey.Copy(c2);return this;}SetAngle(radians){const c=Math.cos(radians);const s=Math.sin(radians);this.ex.Set(c,s);this.ey.Set(-s,c);return this;}Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);return this;}SetIdentity(){this.ex.Set(1,0);this.ey.Set(0,1);return this;}SetZero(){this.ex.SetZero();this.ey.SetZero();return this;}GetAngle(){return Math.atan2(this.ex.y,this.ex.x);}GetInverse(out){const a=this.ex.x;const b=this.ey.x;const c=this.ex.y;const d=this.ey.y;let det=a*d-b*c;if(det!==0){det=1/det;}out.ex.x=det*d;out.ey.x=-det*b;out.ex.y=-det*c;out.ey.y=det*a;return out;}Solve(b_x,b_y,out){const a11=this.ex.x,a12=this.ey.x;const a21=this.ex.y,a22=this.ey.y;let det=a11*a22-a12*a21;if(det!==0){det=1/det;}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out;}SelfAbs(){this.ex.SelfAbs();this.ey.SelfAbs();return this;}SelfInv(){this.GetInverse(this);return this;}SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);return this;}SelfSubM(M){this.ex.SelfSub(M.ex);this.ey.SelfSub(M.ey);return this;}static AbsM(M,out){const M_ex=M.ex,M_ey=M.ey;out.ex.x=b2Abs(M_ex.x);out.ex.y=b2Abs(M_ex.y);out.ey.x=b2Abs(M_ey.x);out.ey.y=b2Abs(M_ey.y);return out;}static MulMV(M,v,out){const M_ex=M.ex,M_ey=M.ey;const v_x=v.x,v_y=v.y;out.x=M_ex.x*v_x+M_ey.x*v_y;out.y=M_ex.y*v_x+M_ey.y*v_y;return out;}static MulTMV(M,v,out){const M_ex=M.ex,M_ey=M.ey;const v_x=v.x,v_y=v.y;out.x=M_ex.x*v_x+M_ex.y*v_y;out.y=M_ey.x*v_x+M_ey.y*v_y;return out;}static AddMM(A,B,out){const A_ex=A.ex,A_ey=A.ey;const B_ex=B.ex,B_ey=B.ey;out.ex.x=A_ex.x+B_ex.x;out.ex.y=A_ex.y+B_ex.y;out.ey.x=A_ey.x+B_ey.x;out.ey.y=A_ey.y+B_ey.y;return out;}static MulMM(A,B,out){const A_ex_x=A.ex.x,A_ex_y=A.ex.y;const A_ey_x=A.ey.x,A_ey_y=A.ey.y;const B_ex_x=B.ex.x,B_ex_y=B.ex.y;const B_ey_x=B.ey.x,B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ey_x*B_ex_y;out.ex.y=A_ex_y*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ey_x*B_ey_y;out.ey.y=A_ex_y*B_ey_x+A_ey_y*B_ey_y;return out;}static MulTMM(A,B,out){const A_ex_x=A.ex.x,A_ex_y=A.ex.y;const A_ey_x=A.ey.x,A_ey_y=A.ey.y;const B_ex_x=B.ex.x,B_ex_y=B.ex.y;const B_ey_x=B.ey.x,B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ex_y*B_ex_y;out.ex.y=A_ey_x*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ex_y*B_ey_y;out.ey.y=A_ey_x*B_ey_x+A_ey_y*B_ey_y;return out;}}b2Mat22.IDENTITY=new b2Mat22();class b2Mat33{constructor(){this.data=new Float32Array([1,0,0,0,1,0,0,0,1]);this.ex=new b2Vec3(this.data.subarray(0,3));this.ey=new b2Vec3(this.data.subarray(3,6));this.ez=new b2Vec3(this.data.subarray(6,9));}Clone(){return new b2Mat33().Copy(this);}SetVVV(c1,c2,c3){this.ex.Copy(c1);this.ey.Copy(c2);this.ez.Copy(c3);return this;}Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);this.ez.Copy(other.ez);return this;}SetIdentity(){this.ex.SetXYZ(1,0,0);this.ey.SetXYZ(0,1,0);this.ez.SetXYZ(0,0,1);return this;}SetZero(){this.ex.SetZero();this.ey.SetZero();this.ez.SetZero();return this;}SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);this.ez.SelfAdd(M.ez);return this;}Solve33(b_x,b_y,b_z,out){const a11=this.ex.x,a21=this.ex.y,a31=this.ex.z;const a12=this.ey.x,a22=this.ey.y,a32=this.ey.z;const a13=this.ez.x,a23=this.ez.y,a33=this.ez.z;let det=a11*(a22*a33-a32*a23)+a21*(a32*a13-a12*a33)+a31*(a12*a23-a22*a13);if(det!==0){det=1/det;}out.x=det*(b_x*(a22*a33-a32*a23)+b_y*(a32*a13-a12*a33)+b_z*(a12*a23-a22*a13));out.y=det*(a11*(b_y*a33-b_z*a23)+a21*(b_z*a13-b_x*a33)+a31*(b_x*a23-b_y*a13));out.z=det*(a11*(a22*b_z-a32*b_y)+a21*(a32*b_x-a12*b_z)+a31*(a12*b_y-a22*b_x));return out;}Solve22(b_x,b_y,out){const a11=this.ex.x,a12=this.ey.x;const a21=this.ex.y,a22=this.ey.y;let det=a11*a22-a12*a21;if(det!==0){det=1/det;}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out;}GetInverse22(M){const a=this.ex.x,b=this.ey.x,c=this.ex.y,d=this.ey.y;let det=a*d-b*c;if(det!==0){det=1/det;}M.ex.x=det*d;M.ey.x=-det*b;M.ex.z=0;M.ex.y=-det*c;M.ey.y=det*a;M.ey.z=0;M.ez.x=0;M.ez.y=0;M.ez.z=0;}GetSymInverse33(M){let det=b2Vec3.DotV3V3(this.ex,b2Vec3.CrossV3V3(this.ey,this.ez,b2Vec3.s_t0));if(det!==0){det=1/det;}const a11=this.ex.x,a12=this.ey.x,a13=this.ez.x;const a22=this.ey.y,a23=this.ez.y;const a33=this.ez.z;M.ex.x=det*(a22*a33-a23*a23);M.ex.y=det*(a13*a23-a12*a33);M.ex.z=det*(a12*a23-a13*a22);M.ey.x=M.ex.y;M.ey.y=det*(a11*a33-a13*a13);M.ey.z=det*(a13*a12-a11*a23);M.ez.x=M.ex.z;M.ez.y=M.ey.z;M.ez.z=det*(a11*a22-a12*a12);}static MulM33V3(A,v,out){const v_x=v.x,v_y=v.y,v_z=v.z;out.x=A.ex.x*v_x+A.ey.x*v_y+A.ez.x*v_z;out.y=A.ex.y*v_x+A.ey.y*v_y+A.ez.y*v_z;out.z=A.ex.z*v_x+A.ey.z*v_y+A.ez.z*v_z;return out;}static MulM33XYZ(A,x,y,z,out){out.x=A.ex.x*x+A.ey.x*y+A.ez.x*z;out.y=A.ex.y*x+A.ey.y*y+A.ez.y*z;out.z=A.ex.z*x+A.ey.z*y+A.ez.z*z;return out;}static MulM33V2(A,v,out){const v_x=v.x,v_y=v.y;out.x=A.ex.x*v_x+A.ey.x*v_y;out.y=A.ex.y*v_x+A.ey.y*v_y;return out;}static MulM33XY(A,x,y,out){out.x=A.ex.x*x+A.ey.x*y;out.y=A.ex.y*x+A.ey.y*y;return out;}}b2Mat33.IDENTITY=new b2Mat33();class b2Rot{constructor(angle=0){this.s=0;this.c=1;if(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);}}Clone(){return new b2Rot().Copy(this);}Copy(other){this.s=other.s;this.c=other.c;return this;}SetAngle(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);return this;}SetIdentity(){this.s=0;this.c=1;return this;}GetAngle(){return Math.atan2(this.s,this.c);}GetXAxis(out){out.x=this.c;out.y=this.s;return out;}GetYAxis(out){out.x=-this.s;out.y=this.c;return out;}static MulRR(q,r,out){const q_c=q.c,q_s=q.s;const r_c=r.c,r_s=r.s;out.s=q_s*r_c+q_c*r_s;out.c=q_c*r_c-q_s*r_s;return out;}static MulTRR(q,r,out){const q_c=q.c,q_s=q.s;const r_c=r.c,r_s=r.s;out.s=q_c*r_s-q_s*r_c;out.c=q_c*r_c+q_s*r_s;return out;}static MulRV(q,v,out){const q_c=q.c,q_s=q.s;const v_x=v.x,v_y=v.y;out.x=q_c*v_x-q_s*v_y;out.y=q_s*v_x+q_c*v_y;return out;}static MulTRV(q,v,out){const q_c=q.c,q_s=q.s;const v_x=v.x,v_y=v.y;out.x=q_c*v_x+q_s*v_y;out.y=-q_s*v_x+q_c*v_y;return out;}}b2Rot.IDENTITY=new b2Rot();class b2Transform{constructor(){this.p=new b2Vec2();this.q=new b2Rot();}Clone(){return new b2Transform().Copy(this);}Copy(other){this.p.Copy(other.p);this.q.Copy(other.q);return this;}SetIdentity(){this.p.SetZero();this.q.SetIdentity();return this;}SetPositionRotation(position,q){this.p.Copy(position);this.q.Copy(q);return this;}SetPositionAngle(pos,a){this.p.Copy(pos);this.q.SetAngle(a);return this;}SetPosition(position){this.p.Copy(position);return this;}SetPositionXY(x,y){this.p.Set(x,y);return this;}SetRotation(rotation){this.q.Copy(rotation);return this;}SetRotationAngle(radians){this.q.SetAngle(radians);return this;}GetPosition(){return this.p;}GetRotation(){return this.q;}GetRotationAngle(){return this.q.GetAngle();}GetAngle(){return this.q.GetAngle();}static MulXV(T,v,out){const T_q_c=T.q.c,T_q_s=T.q.s;const v_x=v.x,v_y=v.y;out.x=T_q_c*v_x-T_q_s*v_y+T.p.x;out.y=T_q_s*v_x+T_q_c*v_y+T.p.y;return out;}static MulTXV(T,v,out){const T_q_c=T.q.c,T_q_s=T.q.s;const p_x=v.x-T.p.x;const p_y=v.y-T.p.y;out.x=T_q_c*p_x+T_q_s*p_y;out.y=-T_q_s*p_x+T_q_c*p_y;return out;}static MulXX(A,B,out){b2Rot.MulRR(A.q,B.q,out.q);b2Vec2.AddVV(b2Rot.MulRV(A.q,B.p,out.p),A.p,out.p);return out;}static MulTXX(A,B,out){b2Rot.MulTRR(A.q,B.q,out.q);b2Rot.MulTRV(A.q,b2Vec2.SubVV(B.p,A.p,out.p),out.p);return out;}}b2Transform.IDENTITY=new b2Transform();class b2Sweep{constructor(){this.localCenter=new b2Vec2();this.c0=new b2Vec2();this.c=new b2Vec2();this.a0=0;this.a=0;this.alpha0=0;}Clone(){return new b2Sweep().Copy(this);}Copy(other){this.localCenter.Copy(other.localCenter);this.c0.Copy(other.c0);this.c.Copy(other.c);this.a0=other.a0;this.a=other.a;this.alpha0=other.alpha0;return this;}GetTransform(xf,beta){const one_minus_beta=1-beta;xf.p.x=one_minus_beta*this.c0.x+beta*this.c.x;xf.p.y=one_minus_beta*this.c0.y+beta*this.c.y;const angle=one_minus_beta*this.a0+beta*this.a;xf.q.SetAngle(angle);xf.p.SelfSub(b2Rot.MulRV(xf.q,this.localCenter,b2Vec2.s_t0));return xf;}Advance(alpha){const beta=(alpha-this.alpha0)/(1-this.alpha0);const one_minus_beta=1-beta;this.c0.x=one_minus_beta*this.c0.x+beta*this.c.x;this.c0.y=one_minus_beta*this.c0.y+beta*this.c.y;this.a0=one_minus_beta*this.a0+beta*this.a;this.alpha0=alpha;}Normalize(){const d=b2_two_pi*Math.floor(this.a0/b2_two_pi);this.a0-=d;this.a-=d;}}class b2Color{constructor(...args){if(args[0]instanceof Float32Array){if(args[0].length!==4){throw new Error();}this.data=args[0];}else {const rr=typeof args[0]==="number"?args[0]:0.5;const gg=typeof args[1]==="number"?args[1]:0.5;const bb=typeof args[2]==="number"?args[2]:0.5;const aa=typeof args[3]==="number"?args[3]:1.0;this.data=new Float32Array([rr,gg,bb,aa]);}}get r(){return this.data[0];}set r(value){this.data[0]=value;}get g(){return this.data[1];}set g(value){this.data[1]=value;}get b(){return this.data[2];}set b(value){this.data[2]=value;}get a(){return this.data[3];}set a(value){this.data[3]=value;}Clone(){return new b2Color().Copy(this);}Copy(other){this.r=other.r;this.g=other.g;this.b=other.b;this.a=other.a;return this;}IsEqual(color){return this.r===color.r&&this.g===color.g&&this.b===color.b&&this.a===color.a;}IsZero(){return this.r===0&&this.g===0&&this.b===0&&this.a===0;}Set(r,g,b,a=this.a){this.SetRGBA(r,g,b,a);}SetByteRGB(r,g,b){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;return this;}SetByteRGBA(r,g,b,a){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;this.a=a/0xff;return this;}SetRGB(rr,gg,bb){this.r=rr;this.g=gg;this.b=bb;return this;}SetRGBA(rr,gg,bb,aa){this.r=rr;this.g=gg;this.b=bb;this.a=aa;return this;}SelfAdd(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;this.a+=color.a;return this;}Add(color,out){out.r=this.r+color.r;out.g=this.g+color.g;out.b=this.b+color.b;out.a=this.a+color.a;return out;}SelfSub(color){this.r-=color.r;this.g-=color.g;this.b-=color.b;this.a-=color.a;return this;}Sub(color,out){out.r=this.r-color.r;out.g=this.g-color.g;out.b=this.b-color.b;out.a=this.a-color.a;return out;}SelfMul(s){this.r*=s;this.g*=s;this.b*=s;this.a*=s;return this;}Mul(s,out){out.r=this.r*s;out.g=this.g*s;out.b=this.b*s;out.a=this.a*s;return out;}Mix(mixColor,strength){b2Color.MixColors(this,mixColor,strength);}static MixColors(colorA,colorB,strength){const dr=strength*(colorB.r-colorA.r);const dg=strength*(colorB.g-colorA.g);const db=strength*(colorB.b-colorA.b);const da=strength*(colorB.a-colorA.a);colorA.r+=dr;colorA.g+=dg;colorA.b+=db;colorA.a+=da;colorB.r-=dr;colorB.g-=dg;colorB.b-=db;colorB.a-=da;}MakeStyleString(alpha=this.a){return b2Color.MakeStyleString(this.r,this.g,this.b,alpha);}static MakeStyleString(r,g,b,a=1.0){r*=255;g*=255;b*=255;if(a<1){return `rgba(${r},${g},${b},${a})`;}else {return `rgb(${r},${g},${b})`;}}}b2Color.ZERO=new b2Color(0,0,0,0);b2Color.RED=new b2Color(1,0,0);b2Color.GREEN=new b2Color(0,1,0);b2Color.BLUE=new b2Color(0,0,1);(function(b2DrawFlags){b2DrawFlags[b2DrawFlags["e_none"]=0]="e_none";b2DrawFlags[b2DrawFlags["e_shapeBit"]=1]="e_shapeBit";b2DrawFlags[b2DrawFlags["e_jointBit"]=2]="e_jointBit";b2DrawFlags[b2DrawFlags["e_aabbBit"]=4]="e_aabbBit";b2DrawFlags[b2DrawFlags["e_pairBit"]=8]="e_pairBit";b2DrawFlags[b2DrawFlags["e_centerOfMassBit"]=16]="e_centerOfMassBit";b2DrawFlags[b2DrawFlags["e_particleBit"]=32]="e_particleBit";b2DrawFlags[b2DrawFlags["e_controllerBit"]=64]="e_controllerBit";b2DrawFlags[b2DrawFlags["e_all"]=63]="e_all";})(exports.b2DrawFlags||(exports.b2DrawFlags={}));class b2Draw{constructor(){this.m_drawFlags=0;}SetFlags(flags){this.m_drawFlags=flags;}GetFlags(){return this.m_drawFlags;}AppendFlags(flags){this.m_drawFlags|=flags;}ClearFlags(flags){this.m_drawFlags&=~flags;}}class b2Timer{constructor(){this.m_start=Date.now();}Reset(){this.m_start=Date.now();return this;}GetMilliseconds(){return Date.now()-this.m_start;}}class b2Counter{constructor(){this.m_count=0;this.m_min_count=0;this.m_max_count=0;}GetCount(){return this.m_count;}GetMinCount(){return this.m_min_count;}GetMaxCount(){return this.m_max_count;}ResetCount(){const count=this.m_count;this.m_count=0;return count;}ResetMinCount(){this.m_min_count=0;}ResetMaxCount(){this.m_max_count=0;}Increment(){this.m_count++;if(this.m_max_count<this.m_count){this.m_max_count=this.m_count;}}Decrement(){this.m_count--;if(this.m_min_count>this.m_count){this.m_min_count=this.m_count;}}}class b2GrowableStack{constructor(N){this.m_stack=[];this.m_count=0;this.m_stack=b2MakeArray(N,index=>null);this.m_count=0;}Reset(){this.m_count=0;return this;}Push(element){this.m_stack[this.m_count]=element;this.m_count++;}Pop(){this.m_count--;const element=this.m_stack[this.m_count];this.m_stack[this.m_count]=null;if(element===null){throw new Error();}return element;}GetCount(){return this.m_count;}}class b2BlockAllocator{}class b2StackAllocator{}class b2DistanceProxy{constructor(){this.m_buffer=b2Vec2.MakeArray(2);this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;}Copy(other){if(other.m_vertices===other.m_buffer){this.m_vertices=this.m_buffer;this.m_buffer[0].Copy(other.m_buffer[0]);this.m_buffer[1].Copy(other.m_buffer[1]);}else {this.m_vertices=other.m_vertices;}this.m_count=other.m_count;this.m_radius=other.m_radius;return this;}Reset(){this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;return this;}SetShape(shape,index){shape.SetupDistanceProxy(this,index);}SetVerticesRadius(vertices,count,radius){this.m_vertices=vertices;this.m_count=count;this.m_radius=radius;}GetSupport(d){let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(let i=1;i<this.m_count;++i){const value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return bestIndex;}GetSupportVertex(d){let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(let i=1;i<this.m_count;++i){const value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return this.m_vertices[bestIndex];}GetVertexCount(){return this.m_count;}GetVertex(index){return this.m_vertices[index];}}class b2SimplexCache{constructor(){this.metric=0;this.count=0;this.indexA=[0,0,0];this.indexB=[0,0,0];}Reset(){this.metric=0;this.count=0;return this;}}class b2DistanceInput{constructor(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.useRadii=false;}Reset(){this.proxyA.Reset();this.proxyB.Reset();this.transformA.SetIdentity();this.transformB.SetIdentity();this.useRadii=false;return this;}}class b2DistanceOutput{constructor(){this.pointA=new b2Vec2();this.pointB=new b2Vec2();this.distance=0;this.iterations=0;}Reset(){this.pointA.SetZero();this.pointB.SetZero();this.distance=0;this.iterations=0;return this;}}class b2ShapeCastInput{constructor(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.translationB=new b2Vec2();}}class b2ShapeCastOutput{constructor(){this.point=new b2Vec2();this.normal=new b2Vec2();this.lambda=0.0;this.iterations=0;}}exports.b2_gjkCalls=0;exports.b2_gjkIters=0;exports.b2_gjkMaxIters=0;function b2_gjk_reset(){exports.b2_gjkCalls=0;exports.b2_gjkIters=0;exports.b2_gjkMaxIters=0;}class b2SimplexVertex{constructor(){this.wA=new b2Vec2();this.wB=new b2Vec2();this.w=new b2Vec2();this.a=0;this.indexA=0;this.indexB=0;}Copy(other){this.wA.Copy(other.wA);this.wB.Copy(other.wB);this.w.Copy(other.w);this.a=other.a;this.indexA=other.indexA;this.indexB=other.indexB;return this;}}class b2Simplex{constructor(){this.m_v1=new b2SimplexVertex();this.m_v2=new b2SimplexVertex();this.m_v3=new b2SimplexVertex();this.m_vertices=[];this.m_count=0;this.m_vertices[0]=this.m_v1;this.m_vertices[1]=this.m_v2;this.m_vertices[2]=this.m_v3;}ReadCache(cache,proxyA,transformA,proxyB,transformB){this.m_count=cache.count;const vertices=this.m_vertices;for(let i=0;i<this.m_count;++i){const v=vertices[i];v.indexA=cache.indexA[i];v.indexB=cache.indexB[i];const wALocal=proxyA.GetVertex(v.indexA);const wBLocal=proxyB.GetVertex(v.indexB);b2Transform.MulXV(transformA,wALocal,v.wA);b2Transform.MulXV(transformB,wBLocal,v.wB);b2Vec2.SubVV(v.wB,v.wA,v.w);v.a=0;}if(this.m_count>1){const metric1=cache.metric;const metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric1<metric2||metric2<b2_epsilon){this.m_count=0;}}if(this.m_count===0){const v=vertices[0];v.indexA=0;v.indexB=0;const wALocal=proxyA.GetVertex(0);const wBLocal=proxyB.GetVertex(0);b2Transform.MulXV(transformA,wALocal,v.wA);b2Transform.MulXV(transformB,wBLocal,v.wB);b2Vec2.SubVV(v.wB,v.wA,v.w);v.a=1;this.m_count=1;}}WriteCache(cache){cache.metric=this.GetMetric();cache.count=this.m_count;const vertices=this.m_vertices;for(let i=0;i<this.m_count;++i){cache.indexA[i]=vertices[i].indexA;cache.indexB[i]=vertices[i].indexB;}}GetSearchDirection(out){switch(this.m_count){case 1:return b2Vec2.NegV(this.m_v1.w,out);case 2:{const e12=b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,out);const sgn=b2Vec2.CrossVV(e12,b2Vec2.NegV(this.m_v1.w,b2Vec2.s_t0));if(sgn>0){return b2Vec2.CrossOneV(e12,out);}else {return b2Vec2.CrossVOne(e12,out);}}default:return out.SetZero();}}GetClosestPoint(out){switch(this.m_count){case 0:return out.SetZero();case 1:return out.Copy(this.m_v1.w);case 2:return out.Set(this.m_v1.a*this.m_v1.w.x+this.m_v2.a*this.m_v2.w.x,this.m_v1.a*this.m_v1.w.y+this.m_v2.a*this.m_v2.w.y);case 3:return out.SetZero();default:return out.SetZero();}}GetWitnessPoints(pA,pB){switch(this.m_count){case 0:break;case 1:pA.Copy(this.m_v1.wA);pB.Copy(this.m_v1.wB);break;case 2:pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x;pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y;pB.x=this.m_v1.a*this.m_v1.wB.x+this.m_v2.a*this.m_v2.wB.x;pB.y=this.m_v1.a*this.m_v1.wB.y+this.m_v2.a*this.m_v2.wB.y;break;case 3:pB.x=pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x+this.m_v3.a*this.m_v3.wA.x;pB.y=pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y+this.m_v3.a*this.m_v3.wA.y;break;}}GetMetric(){switch(this.m_count){case 0:return 0;case 1:return 0;case 2:return b2Vec2.DistanceVV(this.m_v1.w,this.m_v2.w);case 3:return b2Vec2.CrossVV(b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,b2Vec2.s_t0),b2Vec2.SubVV(this.m_v3.w,this.m_v1.w,b2Vec2.s_t1));default:return 0;}}Solve2(){const w1=this.m_v1.w;const w2=this.m_v2.w;const e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);const d12_2=-b2Vec2.DotVV(w1,e12);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return;}const d12_1=b2Vec2.DotVV(w2,e12);if(d12_1<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return;}const inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2;}Solve3(){const w1=this.m_v1.w;const w2=this.m_v2.w;const w3=this.m_v3.w;const e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);const w1e12=b2Vec2.DotVV(w1,e12);const w2e12=b2Vec2.DotVV(w2,e12);const d12_1=w2e12;const d12_2=-w1e12;const e13=b2Vec2.SubVV(w3,w1,b2Simplex.s_e13);const w1e13=b2Vec2.DotVV(w1,e13);const w3e13=b2Vec2.DotVV(w3,e13);const d13_1=w3e13;const d13_2=-w1e13;const e23=b2Vec2.SubVV(w3,w2,b2Simplex.s_e23);const w2e23=b2Vec2.DotVV(w2,e23);const w3e23=b2Vec2.DotVV(w3,e23);const d23_1=w3e23;const d23_2=-w2e23;const n123=b2Vec2.CrossVV(e12,e13);const d123_1=n123*b2Vec2.CrossVV(w2,w3);const d123_2=n123*b2Vec2.CrossVV(w3,w1);const d123_3=n123*b2Vec2.CrossVV(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return;}if(d12_1>0&&d12_2>0&&d123_3<=0){const inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2;return;}if(d13_1>0&&d13_2>0&&d123_2<=0){const inv_d13=1/(d13_1+d13_2);this.m_v1.a=d13_1*inv_d13;this.m_v3.a=d13_2*inv_d13;this.m_count=2;this.m_v2.Copy(this.m_v3);return;}if(d12_1<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return;}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Copy(this.m_v3);return;}if(d23_1>0&&d23_2>0&&d123_1<=0){const inv_d23=1/(d23_1+d23_2);this.m_v2.a=d23_1*inv_d23;this.m_v3.a=d23_2*inv_d23;this.m_count=2;this.m_v1.Copy(this.m_v3);return;}const inv_d123=1/(d123_1+d123_2+d123_3);this.m_v1.a=d123_1*inv_d123;this.m_v2.a=d123_2*inv_d123;this.m_v3.a=d123_3*inv_d123;this.m_count=3;}}b2Simplex.s_e12=new b2Vec2();b2Simplex.s_e13=new b2Vec2();b2Simplex.s_e23=new b2Vec2();const b2Distance_s_simplex=new b2Simplex();const b2Distance_s_saveA=[0,0,0];const b2Distance_s_saveB=[0,0,0];const b2Distance_s_p=new b2Vec2();const b2Distance_s_d=new b2Vec2();const b2Distance_s_normal=new b2Vec2();const b2Distance_s_supportA=new b2Vec2();const b2Distance_s_supportB=new b2Vec2();function b2Distance(output,cache,input){++exports.b2_gjkCalls;const proxyA=input.proxyA;const proxyB=input.proxyB;const transformA=input.transformA;const transformB=input.transformB;const simplex=b2Distance_s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);const vertices=simplex.m_vertices;const k_maxIters=20;const saveA=b2Distance_s_saveA;const saveB=b2Distance_s_saveB;let saveCount=0;let iter=0;while(iter<k_maxIters){saveCount=simplex.m_count;for(let i=0;i<saveCount;++i){saveA[i]=vertices[i].indexA;saveB[i]=vertices[i].indexB;}switch(simplex.m_count){case 1:break;case 2:simplex.Solve2();break;case 3:simplex.Solve3();break;}if(simplex.m_count===3){break;}const d=simplex.GetSearchDirection(b2Distance_s_d);if(d.LengthSquared()<b2_epsilon_sq){break;}const vertex=vertices[simplex.m_count];vertex.indexA=proxyA.GetSupport(b2Rot.MulTRV(transformA.q,b2Vec2.NegV(d,b2Vec2.s_t0),b2Distance_s_supportA));b2Transform.MulXV(transformA,proxyA.GetVertex(vertex.indexA),vertex.wA);vertex.indexB=proxyB.GetSupport(b2Rot.MulTRV(transformB.q,d,b2Distance_s_supportB));b2Transform.MulXV(transformB,proxyB.GetVertex(vertex.indexB),vertex.wB);b2Vec2.SubVV(vertex.wB,vertex.wA,vertex.w);++iter;++exports.b2_gjkIters;let duplicate=false;for(let i=0;i<saveCount;++i){if(vertex.indexA===saveA[i]&&vertex.indexB===saveB[i]){duplicate=true;break;}}if(duplicate){break;}++simplex.m_count;}exports.b2_gjkMaxIters=b2Max(exports.b2_gjkMaxIters,iter);simplex.GetWitnessPoints(output.pointA,output.pointB);output.distance=b2Vec2.DistanceVV(output.pointA,output.pointB);output.iterations=iter;simplex.WriteCache(cache);if(input.useRadii){const rA=proxyA.m_radius;const rB=proxyB.m_radius;if(output.distance>rA+rB&&output.distance>b2_epsilon){output.distance-=rA+rB;const normal=b2Vec2.SubVV(output.pointB,output.pointA,b2Distance_s_normal);normal.Normalize();output.pointA.SelfMulAdd(rA,normal);output.pointB.SelfMulSub(rB,normal);}else {const p=b2Vec2.MidVV(output.pointA,output.pointB,b2Distance_s_p);output.pointA.Copy(p);output.pointB.Copy(p);output.distance=0;}}}const b2ShapeCast_s_n=new b2Vec2();const b2ShapeCast_s_simplex=new b2Simplex();const b2ShapeCast_s_wA=new b2Vec2();const b2ShapeCast_s_wB=new b2Vec2();const b2ShapeCast_s_v=new b2Vec2();const b2ShapeCast_s_p=new b2Vec2();const b2ShapeCast_s_pointA=new b2Vec2();const b2ShapeCast_s_pointB=new b2Vec2();function b2ShapeCast(output,input){output.iterations=0;output.lambda=1.0;output.normal.SetZero();output.point.SetZero();const proxyA=input.proxyA;const proxyB=input.proxyB;const radiusA=b2Max(proxyA.m_radius,b2_polygonRadius);const radiusB=b2Max(proxyB.m_radius,b2_polygonRadius);const radius=radiusA+radiusB;const xfA=input.transformA;const xfB=input.transformB;const r=input.translationB;const n=b2ShapeCast_s_n.Set(0.0,0.0);let lambda=0.0;const simplex=b2ShapeCast_s_simplex;simplex.m_count=0;const vertices=simplex.m_vertices;let indexA=proxyA.GetSupport(b2Rot.MulTRV(xfA.q,b2Vec2.NegV(r,b2Vec2.s_t1),b2Vec2.s_t0));let wA=b2Transform.MulXV(xfA,proxyA.GetVertex(indexA),b2ShapeCast_s_wA);let indexB=proxyB.GetSupport(b2Rot.MulTRV(xfB.q,r,b2Vec2.s_t0));let wB=b2Transform.MulXV(xfB,proxyB.GetVertex(indexB),b2ShapeCast_s_wB);const v=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_v);const sigma=b2Max(b2_polygonRadius,radius-b2_polygonRadius);const tolerance=0.5*b2_linearSlop;const k_maxIters=20;let iter=0;while(iter<k_maxIters&&b2Abs(v.Length()-sigma)>tolerance){output.iterations+=1;indexA=proxyA.GetSupport(b2Rot.MulTRV(xfA.q,b2Vec2.NegV(v,b2Vec2.s_t1),b2Vec2.s_t0));wA=b2Transform.MulXV(xfA,proxyA.GetVertex(indexA),b2ShapeCast_s_wA);indexB=proxyB.GetSupport(b2Rot.MulTRV(xfB.q,v,b2Vec2.s_t0));wB=b2Transform.MulXV(xfB,proxyB.GetVertex(indexB),b2ShapeCast_s_wB);const p=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_p);v.Normalize();const vp=b2Vec2.DotVV(v,p);const vr=b2Vec2.DotVV(v,r);if(vp-sigma>lambda*vr){if(vr<=0.0){return false;}lambda=(vp-sigma)/vr;if(lambda>1.0){return false;}n.Copy(v).SelfNeg();simplex.m_count=0;}const vertex=vertices[simplex.m_count];vertex.indexA=indexB;vertex.wA.Copy(wB).SelfMulAdd(lambda,r);vertex.indexB=indexA;vertex.wB.Copy(wA);vertex.w.Copy(vertex.wB).SelfSub(vertex.wA);vertex.a=1.0;simplex.m_count+=1;switch(simplex.m_count){case 1:break;case 2:simplex.Solve2();break;case 3:simplex.Solve3();break;}if(simplex.m_count===3){return false;}simplex.GetClosestPoint(v);++iter;}const pointA=b2ShapeCast_s_pointA;const pointB=b2ShapeCast_s_pointB;simplex.GetWitnessPoints(pointA,pointB);if(v.LengthSquared()>0.0){n.Copy(v).SelfNeg();n.Normalize();}output.normal.Copy(n);output.lambda=lambda;output.iterations=iter;return true;}(function(b2ContactFeatureType){b2ContactFeatureType[b2ContactFeatureType["e_vertex"]=0]="e_vertex";b2ContactFeatureType[b2ContactFeatureType["e_face"]=1]="e_face";})(exports.b2ContactFeatureType||(exports.b2ContactFeatureType={}));class b2ContactFeature{constructor(){this._key=0;this._key_invalid=false;this._indexA=0;this._indexB=0;this._typeA=0;this._typeB=0;}get key(){if(this._key_invalid){this._key_invalid=false;this._key=this._indexA|this._indexB<<8|this._typeA<<16|this._typeB<<24;}return this._key;}set key(value){this._key=value;this._key_invalid=false;this._indexA=this._key&0xff;this._indexB=this._key>>8&0xff;this._typeA=this._key>>16&0xff;this._typeB=this._key>>24&0xff;}get indexA(){return this._indexA;}set indexA(value){this._indexA=value;this._key_invalid=true;}get indexB(){return this._indexB;}set indexB(value){this._indexB=value;this._key_invalid=true;}get typeA(){return this._typeA;}set typeA(value){this._typeA=value;this._key_invalid=true;}get typeB(){return this._typeB;}set typeB(value){this._typeB=value;this._key_invalid=true;}}class b2ContactID{constructor(){this.cf=new b2ContactFeature();}Copy(o){this.key=o.key;return this;}Clone(){return new b2ContactID().Copy(this);}get key(){return this.cf.key;}set key(value){this.cf.key=value;}}class b2ManifoldPoint{constructor(){this.localPoint=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.id=new b2ContactID();}static MakeArray(length){return b2MakeArray(length,i=>new b2ManifoldPoint());}Reset(){this.localPoint.SetZero();this.normalImpulse=0;this.tangentImpulse=0;this.id.key=0;}Copy(o){this.localPoint.Copy(o.localPoint);this.normalImpulse=o.normalImpulse;this.tangentImpulse=o.tangentImpulse;this.id.Copy(o.id);return this;}}(function(b2ManifoldType){b2ManifoldType[b2ManifoldType["e_unknown"]=-1]="e_unknown";b2ManifoldType[b2ManifoldType["e_circles"]=0]="e_circles";b2ManifoldType[b2ManifoldType["e_faceA"]=1]="e_faceA";b2ManifoldType[b2ManifoldType["e_faceB"]=2]="e_faceB";})(exports.b2ManifoldType||(exports.b2ManifoldType={}));class b2Manifold{constructor(){this.points=b2ManifoldPoint.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2();this.localPoint=new b2Vec2();this.type=exports.b2ManifoldType.e_unknown;this.pointCount=0;}Reset(){for(let i=0;i<b2_maxManifoldPoints;++i){this.points[i].Reset();}this.localNormal.SetZero();this.localPoint.SetZero();this.type=exports.b2ManifoldType.e_unknown;this.pointCount=0;}Copy(o){this.pointCount=o.pointCount;for(let i=0;i<b2_maxManifoldPoints;++i){this.points[i].Copy(o.points[i]);}this.localNormal.Copy(o.localNormal);this.localPoint.Copy(o.localPoint);this.type=o.type;return this;}Clone(){return new b2Manifold().Copy(this);}}class b2WorldManifold{constructor(){this.normal=new b2Vec2();this.points=b2Vec2.MakeArray(b2_maxManifoldPoints);this.separations=b2MakeNumberArray(b2_maxManifoldPoints);}Initialize(manifold,xfA,radiusA,xfB,radiusB){if(manifold.pointCount===0){return;}switch(manifold.type){case exports.b2ManifoldType.e_circles:{this.normal.Set(1,0);const pointA=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_pointA);const pointB=b2Transform.MulXV(xfB,manifold.points[0].localPoint,b2WorldManifold.Initialize_s_pointB);if(b2Vec2.DistanceSquaredVV(pointA,pointB)>b2_epsilon_sq){b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize();}const cA=b2Vec2.AddVMulSV(pointA,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);const cB=b2Vec2.SubVMulSV(pointB,radiusB,this.normal,b2WorldManifold.Initialize_s_cB);b2Vec2.MidVV(cA,cB,this.points[0]);this.separations[0]=b2Vec2.DotVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),this.normal);break;}case exports.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,manifold.localNormal,this.normal);const planePoint=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(let i=0;i<manifold.pointCount;++i){const clipPoint=b2Transform.MulXV(xfB,manifold.points[i].localPoint,b2WorldManifold.Initialize_s_clipPoint);const s=radiusA-b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal);const cA=b2Vec2.AddVMulSV(clipPoint,s,this.normal,b2WorldManifold.Initialize_s_cA);const cB=b2Vec2.SubVMulSV(clipPoint,radiusB,this.normal,b2WorldManifold.Initialize_s_cB);b2Vec2.MidVV(cA,cB,this.points[i]);this.separations[i]=b2Vec2.DotVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),this.normal);}break;}case exports.b2ManifoldType.e_faceB:{b2Rot.MulRV(xfB.q,manifold.localNormal,this.normal);const planePoint=b2Transform.MulXV(xfB,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(let i=0;i<manifold.pointCount;++i){const clipPoint=b2Transform.MulXV(xfA,manifold.points[i].localPoint,b2WorldManifold.Initialize_s_clipPoint);const s=radiusB-b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal);const cB=b2Vec2.AddVMulSV(clipPoint,s,this.normal,b2WorldManifold.Initialize_s_cB);const cA=b2Vec2.SubVMulSV(clipPoint,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);b2Vec2.MidVV(cA,cB,this.points[i]);this.separations[i]=b2Vec2.DotVV(b2Vec2.SubVV(cA,cB,b2Vec2.s_t0),this.normal);}this.normal.SelfNeg();break;}}}}b2WorldManifold.Initialize_s_pointA=new b2Vec2();b2WorldManifold.Initialize_s_pointB=new b2Vec2();b2WorldManifold.Initialize_s_cA=new b2Vec2();b2WorldManifold.Initialize_s_cB=new b2Vec2();b2WorldManifold.Initialize_s_planePoint=new b2Vec2();b2WorldManifold.Initialize_s_clipPoint=new b2Vec2();(function(b2PointState){b2PointState[b2PointState["b2_nullState"]=0]="b2_nullState";b2PointState[b2PointState["b2_addState"]=1]="b2_addState";b2PointState[b2PointState["b2_persistState"]=2]="b2_persistState";b2PointState[b2PointState["b2_removeState"]=3]="b2_removeState";})(exports.b2PointState||(exports.b2PointState={}));function b2GetPointStates(state1,state2,manifold1,manifold2){let i;for(i=0;i<manifold1.pointCount;++i){const id=manifold1.points[i].id;const key=id.key;state1[i]=exports.b2PointState.b2_removeState;for(let j=0,jct=manifold2.pointCount;j<jct;++j){if(manifold2.points[j].id.key===key){state1[i]=exports.b2PointState.b2_persistState;break;}}}for(;i<b2_maxManifoldPoints;++i){state1[i]=exports.b2PointState.b2_nullState;}for(i=0;i<manifold2.pointCount;++i){const id=manifold2.points[i].id;const key=id.key;state2[i]=exports.b2PointState.b2_addState;for(let j=0,jct=manifold1.pointCount;j<jct;++j){if(manifold1.points[j].id.key===key){state2[i]=exports.b2PointState.b2_persistState;break;}}}for(;i<b2_maxManifoldPoints;++i){state2[i]=exports.b2PointState.b2_nullState;}}class b2ClipVertex{constructor(){this.v=new b2Vec2();this.id=new b2ContactID();}static MakeArray(length){return b2MakeArray(length,i=>new b2ClipVertex());}Copy(other){this.v.Copy(other.v);this.id.Copy(other.id);return this;}}class b2RayCastInput{constructor(){this.p1=new b2Vec2();this.p2=new b2Vec2();this.maxFraction=1;}Copy(o){this.p1.Copy(o.p1);this.p2.Copy(o.p2);this.maxFraction=o.maxFraction;return this;}}class b2RayCastOutput{constructor(){this.normal=new b2Vec2();this.fraction=0;}Copy(o){this.normal.Copy(o.normal);this.fraction=o.fraction;return this;}}class b2AABB{constructor(){this.lowerBound=new b2Vec2();this.upperBound=new b2Vec2();this.m_cache_center=new b2Vec2();this.m_cache_extent=new b2Vec2();}Copy(o){this.lowerBound.Copy(o.lowerBound);this.upperBound.Copy(o.upperBound);return this;}IsValid(){if(!this.lowerBound.IsValid()){return false;}if(!this.upperBound.IsValid()){return false;}if(this.upperBound.x<this.lowerBound.x){return false;}if(this.upperBound.y<this.lowerBound.y){return false;}return true;}GetCenter(){return b2Vec2.MidVV(this.lowerBound,this.upperBound,this.m_cache_center);}GetExtents(){return b2Vec2.ExtVV(this.lowerBound,this.upperBound,this.m_cache_extent);}GetPerimeter(){const wx=this.upperBound.x-this.lowerBound.x;const wy=this.upperBound.y-this.lowerBound.y;return 2*(wx+wy);}Combine1(aabb){this.lowerBound.x=b2Min(this.lowerBound.x,aabb.lowerBound.x);this.lowerBound.y=b2Min(this.lowerBound.y,aabb.lowerBound.y);this.upperBound.x=b2Max(this.upperBound.x,aabb.upperBound.x);this.upperBound.y=b2Max(this.upperBound.y,aabb.upperBound.y);return this;}Combine2(aabb1,aabb2){this.lowerBound.x=b2Min(aabb1.lowerBound.x,aabb2.lowerBound.x);this.lowerBound.y=b2Min(aabb1.lowerBound.y,aabb2.lowerBound.y);this.upperBound.x=b2Max(aabb1.upperBound.x,aabb2.upperBound.x);this.upperBound.y=b2Max(aabb1.upperBound.y,aabb2.upperBound.y);return this;}static Combine(aabb1,aabb2,out){out.Combine2(aabb1,aabb2);return out;}Contains(aabb){if(this.lowerBound.x<=aabb.lowerBound.x){return false;}if(this.lowerBound.y<=aabb.lowerBound.y){return false;}if(aabb.upperBound.x<=this.upperBound.x){return false;}if(aabb.upperBound.y<=this.upperBound.y){return false;}return true;}RayCast(output,input){let tmin=-b2_maxFloat;let tmax=b2_maxFloat;const p_x=input.p1.x;const p_y=input.p1.y;const d_x=input.p2.x-input.p1.x;const d_y=input.p2.y-input.p1.y;const absD_x=b2Abs(d_x);const absD_y=b2Abs(d_y);const normal=output.normal;if(absD_x<b2_epsilon){if(p_x<this.lowerBound.x||this.upperBound.x<p_x){return false;}}else {const inv_d=1/d_x;let t1=(this.lowerBound.x-p_x)*inv_d;let t2=(this.upperBound.x-p_x)*inv_d;let s=-1;if(t1>t2){const t3=t1;t1=t2;t2=t3;s=1;}if(t1>tmin){normal.x=s;normal.y=0;tmin=t1;}tmax=b2Min(tmax,t2);if(tmin>tmax){return false;}}if(absD_y<b2_epsilon){if(p_y<this.lowerBound.y||this.upperBound.y<p_y){return false;}}else {const inv_d=1/d_y;let t1=(this.lowerBound.y-p_y)*inv_d;let t2=(this.upperBound.y-p_y)*inv_d;let s=-1;if(t1>t2){const t3=t1;t1=t2;t2=t3;s=1;}if(t1>tmin){normal.x=0;normal.y=s;tmin=t1;}tmax=b2Min(tmax,t2);if(tmin>tmax){return false;}}if(tmin<0||input.maxFraction<tmin){return false;}output.fraction=tmin;return true;}TestContain(point){if(point.x<this.lowerBound.x||this.upperBound.x<point.x){return false;}if(point.y<this.lowerBound.y||this.upperBound.y<point.y){return false;}return true;}TestOverlap(other){if(this.upperBound.x<other.lowerBound.x){return false;}if(this.upperBound.y<other.lowerBound.y){return false;}if(other.upperBound.x<this.lowerBound.x){return false;}if(other.upperBound.y<this.lowerBound.y){return false;}return true;}}function b2TestOverlapAABB(a,b){if(a.upperBound.x<b.lowerBound.x){return false;}if(a.upperBound.y<b.lowerBound.y){return false;}if(b.upperBound.x<a.lowerBound.x){return false;}if(b.upperBound.y<a.lowerBound.y){return false;}return true;}function b2ClipSegmentToLine(vOut,vIn,normal,offset,vertexIndexA){let numOut=0;const vIn0=vIn[0];const vIn1=vIn[1];const distance0=b2Vec2.DotVV(normal,vIn0.v)-offset;const distance1=b2Vec2.DotVV(normal,vIn1.v)-offset;if(distance0<=0){vOut[numOut++].Copy(vIn0);}if(distance1<=0){vOut[numOut++].Copy(vIn1);}if(distance0*distance1<0){const interp=distance0/(distance0-distance1);const v=vOut[numOut].v;v.x=vIn0.v.x+interp*(vIn1.v.x-vIn0.v.x);v.y=vIn0.v.y+interp*(vIn1.v.y-vIn0.v.y);const id=vOut[numOut].id;id.cf.indexA=vertexIndexA;id.cf.indexB=vIn0.id.cf.indexB;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;id.cf.typeB=exports.b2ContactFeatureType.e_face;++numOut;}return numOut;}const b2TestOverlapShape_s_input=new b2DistanceInput();const b2TestOverlapShape_s_simplexCache=new b2SimplexCache();const b2TestOverlapShape_s_output=new b2DistanceOutput();function b2TestOverlapShape(shapeA,indexA,shapeB,indexB,xfA,xfB){const input=b2TestOverlapShape_s_input.Reset();input.proxyA.SetShape(shapeA,indexA);input.proxyB.SetShape(shapeB,indexB);input.transformA.Copy(xfA);input.transformB.Copy(xfB);input.useRadii=true;const simplexCache=b2TestOverlapShape_s_simplexCache.Reset();simplexCache.count=0;const output=b2TestOverlapShape_s_output.Reset();b2Distance(output,simplexCache,input);return output.distance<10*b2_epsilon;}function verify(value){if(value===null){throw new Error();}return value;}class b2TreeNode{constructor(id=0){this.m_id=0;this.aabb=new b2AABB();this._userData=null;this.parent=null;this.child1=null;this.child2=null;this.height=0;this.m_id=id;}get userData(){if(this._userData===null){throw new Error();}return this._userData;}set userData(value){if(this._userData!==null){throw new Error();}this._userData=value;}Reset(){this._userData=null;}IsLeaf(){return this.child1===null;}}class b2DynamicTree{constructor(){this.m_root=null;this.m_freeList=null;this.m_path=0;this.m_insertionCount=0;this.m_stack=new b2GrowableStack(256);}Query(aabb,callback){const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(node===null){continue;}if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){const proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}}QueryPoint(point,callback){const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(node===null){continue;}if(node.aabb.TestContain(point)){if(node.IsLeaf()){const proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}}RayCast(input,callback){const p1=input.p1;const p2=input.p2;const r=b2Vec2.SubVV(p2,p1,b2DynamicTree.s_r);r.Normalize();const v=b2Vec2.CrossOneV(r,b2DynamicTree.s_v);const abs_v=b2Vec2.AbsV(v,b2DynamicTree.s_abs_v);let maxFraction=input.maxFraction;const segmentAABB=b2DynamicTree.s_segmentAABB;let t_x=p1.x+maxFraction*(p2.x-p1.x);let t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y);const stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){const node=stack.Pop();if(node===null){continue;}if(!b2TestOverlapAABB(node.aabb,segmentAABB)){continue;}const c=node.aabb.GetCenter();const h=node.aabb.GetExtents();const separation=b2Abs(b2Vec2.DotVV(v,b2Vec2.SubVV(p1,c,b2Vec2.s_t0)))-b2Vec2.DotVV(abs_v,h);if(separation>0){continue;}if(node.IsLeaf()){const subInput=b2DynamicTree.s_subInput;subInput.p1.Copy(input.p1);subInput.p2.Copy(input.p2);subInput.maxFraction=maxFraction;const value=callback(subInput,node);if(value===0){return;}if(value>0){maxFraction=value;t_x=p1.x+maxFraction*(p2.x-p1.x);t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y);}}else {stack.Push(node.child1);stack.Push(node.child2);}}}AllocateNode(){if(this.m_freeList!==null){const node=this.m_freeList;this.m_freeList=node.parent;node.parent=null;node.child1=null;node.child2=null;node.height=0;return node;}return new b2TreeNode(b2DynamicTree.s_node_id++);}FreeNode(node){node.parent=this.m_freeList;node.child1=null;node.child2=null;node.height=-1;node.Reset();this.m_freeList=node;}CreateProxy(aabb,userData){const node=this.AllocateNode();const r_x=b2_aabbExtension;const r_y=b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-r_x;node.aabb.lowerBound.y=aabb.lowerBound.y-r_y;node.aabb.upperBound.x=aabb.upperBound.x+r_x;node.aabb.upperBound.y=aabb.upperBound.y+r_y;node.userData=userData;node.height=0;this.InsertLeaf(node);return node;}DestroyProxy(node){this.RemoveLeaf(node);this.FreeNode(node);}MoveProxy(node,aabb,displacement){if(node.aabb.Contains(aabb)){return false;}this.RemoveLeaf(node);const r_x=b2_aabbExtension;const r_y=b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-r_x;node.aabb.lowerBound.y=aabb.lowerBound.y-r_y;node.aabb.upperBound.x=aabb.upperBound.x+r_x;node.aabb.upperBound.y=aabb.upperBound.y+r_y;const d_x=b2_aabbMultiplier*displacement.x;const d_y=b2_aabbMultiplier*displacement.y;if(d_x<0.0){node.aabb.lowerBound.x+=d_x;}else {node.aabb.upperBound.x+=d_x;}if(d_y<0.0){node.aabb.lowerBound.y+=d_y;}else {node.aabb.upperBound.y+=d_y;}this.InsertLeaf(node);return true;}InsertLeaf(leaf){++this.m_insertionCount;if(this.m_root===null){this.m_root=leaf;this.m_root.parent=null;return;}const leafAABB=leaf.aabb;let sibling=this.m_root;while(!sibling.IsLeaf()){const child1=verify(sibling.child1);const child2=verify(sibling.child2);const area=sibling.aabb.GetPerimeter();const combinedAABB=b2DynamicTree.s_combinedAABB;combinedAABB.Combine2(sibling.aabb,leafAABB);const combinedArea=combinedAABB.GetPerimeter();const cost=2*combinedArea;const inheritanceCost=2*(combinedArea-area);let cost1;const aabb=b2DynamicTree.s_aabb;let oldArea;let newArea;if(child1.IsLeaf()){aabb.Combine2(leafAABB,child1.aabb);cost1=aabb.GetPerimeter()+inheritanceCost;}else {aabb.Combine2(leafAABB,child1.aabb);oldArea=child1.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost1=newArea-oldArea+inheritanceCost;}let cost2;if(child2.IsLeaf()){aabb.Combine2(leafAABB,child2.aabb);cost2=aabb.GetPerimeter()+inheritanceCost;}else {aabb.Combine2(leafAABB,child2.aabb);oldArea=child2.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost2=newArea-oldArea+inheritanceCost;}if(cost<cost1&&cost<cost2){break;}if(cost1<cost2){sibling=child1;}else {sibling=child2;}}const oldParent=sibling.parent;const newParent=this.AllocateNode();newParent.parent=oldParent;newParent.aabb.Combine2(leafAABB,sibling.aabb);newParent.height=sibling.height+1;if(oldParent!==null){if(oldParent.child1===sibling){oldParent.child1=newParent;}else {oldParent.child2=newParent;}newParent.child1=sibling;newParent.child2=leaf;sibling.parent=newParent;leaf.parent=newParent;}else {newParent.child1=sibling;newParent.child2=leaf;sibling.parent=newParent;leaf.parent=newParent;this.m_root=newParent;}let node=leaf.parent;while(node!==null){node=this.Balance(node);const child1=verify(node.child1);const child2=verify(node.child2);node.height=1+b2Max(child1.height,child2.height);node.aabb.Combine2(child1.aabb,child2.aabb);node=node.parent;}}RemoveLeaf(leaf){if(leaf===this.m_root){this.m_root=null;return;}const parent=verify(leaf.parent);const grandParent=parent&&parent.parent;const sibling=verify(parent.child1===leaf?parent.child2:parent.child1);if(grandParent!==null){if(grandParent.child1===parent){grandParent.child1=sibling;}else {grandParent.child2=sibling;}sibling.parent=grandParent;this.FreeNode(parent);let index=grandParent;while(index!==null){index=this.Balance(index);const child1=verify(index.child1);const child2=verify(index.child2);index.aabb.Combine2(child1.aabb,child2.aabb);index.height=1+b2Max(child1.height,child2.height);index=index.parent;}}else {this.m_root=sibling;sibling.parent=null;this.FreeNode(parent);}}Balance(A){if(A.IsLeaf()||A.height<2){return A;}const B=verify(A.child1);const C=verify(A.child2);const balance=C.height-B.height;if(balance>1){const F=verify(C.child1);const G=verify(C.child2);C.child1=A;C.parent=A.parent;A.parent=C;if(C.parent!==null){if(C.parent.child1===A){C.parent.child1=C;}else {C.parent.child2=C;}}else {this.m_root=C;}if(F.height>G.height){C.child2=F;A.child2=G;G.parent=A;A.aabb.Combine2(B.aabb,G.aabb);C.aabb.Combine2(A.aabb,F.aabb);A.height=1+b2Max(B.height,G.height);C.height=1+b2Max(A.height,F.height);}else {C.child2=G;A.child2=F;F.parent=A;A.aabb.Combine2(B.aabb,F.aabb);C.aabb.Combine2(A.aabb,G.aabb);A.height=1+b2Max(B.height,F.height);C.height=1+b2Max(A.height,G.height);}return C;}if(balance<-1){const D=verify(B.child1);const E=verify(B.child2);B.child1=A;B.parent=A.parent;A.parent=B;if(B.parent!==null){if(B.parent.child1===A){B.parent.child1=B;}else {B.parent.child2=B;}}else {this.m_root=B;}if(D.height>E.height){B.child2=D;A.child1=E;E.parent=A;A.aabb.Combine2(C.aabb,E.aabb);B.aabb.Combine2(A.aabb,D.aabb);A.height=1+b2Max(C.height,E.height);B.height=1+b2Max(A.height,D.height);}else {B.child2=E;A.child1=D;D.parent=A;A.aabb.Combine2(C.aabb,D.aabb);B.aabb.Combine2(A.aabb,E.aabb);A.height=1+b2Max(C.height,D.height);B.height=1+b2Max(A.height,E.height);}return B;}return A;}GetHeight(){if(this.m_root===null){return 0;}return this.m_root.height;}static GetAreaNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}let area=node.aabb.GetPerimeter();area+=b2DynamicTree.GetAreaNode(node.child1);area+=b2DynamicTree.GetAreaNode(node.child2);return area;}GetAreaRatio(){if(this.m_root===null){return 0;}const root=this.m_root;const rootArea=root.aabb.GetPerimeter();const totalArea=b2DynamicTree.GetAreaNode(this.m_root);return totalArea/rootArea;}static ComputeHeightNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}const height1=b2DynamicTree.ComputeHeightNode(node.child1);const height2=b2DynamicTree.ComputeHeightNode(node.child2);return 1+b2Max(height1,height2);}ComputeHeight(){const height=b2DynamicTree.ComputeHeightNode(this.m_root);return height;}ValidateStructure(node){if(node===null){return;}if(node===this.m_root);if(node.IsLeaf()){return;}const child1=verify(node.child1);const child2=verify(node.child2);this.ValidateStructure(child1);this.ValidateStructure(child2);}ValidateMetrics(node){if(node===null){return;}if(node.IsLeaf()){return;}const child1=verify(node.child1);const child2=verify(node.child2);const aabb=b2DynamicTree.s_aabb;aabb.Combine2(child1.aabb,child2.aabb);this.ValidateMetrics(child1);this.ValidateMetrics(child2);}Validate(){}static GetMaxBalanceNode(node,maxBalance){if(node===null){return maxBalance;}if(node.height<=1){return maxBalance;}const child1=verify(node.child1);const child2=verify(node.child2);const balance=b2Abs(child2.height-child1.height);return b2Max(maxBalance,balance);}GetMaxBalance(){const maxBalance=b2DynamicTree.GetMaxBalanceNode(this.m_root,0);return maxBalance;}RebuildBottomUp(){this.Validate();}static ShiftOriginNode(node,newOrigin){if(node===null){return;}if(node.height<=1){return;}const child1=node.child1;const child2=node.child2;b2DynamicTree.ShiftOriginNode(child1,newOrigin);b2DynamicTree.ShiftOriginNode(child2,newOrigin);node.aabb.lowerBound.SelfSub(newOrigin);node.aabb.upperBound.SelfSub(newOrigin);}ShiftOrigin(newOrigin){b2DynamicTree.ShiftOriginNode(this.m_root,newOrigin);}}b2DynamicTree.s_r=new b2Vec2();b2DynamicTree.s_v=new b2Vec2();b2DynamicTree.s_abs_v=new b2Vec2();b2DynamicTree.s_segmentAABB=new b2AABB();b2DynamicTree.s_subInput=new b2RayCastInput();b2DynamicTree.s_combinedAABB=new b2AABB();b2DynamicTree.s_aabb=new b2AABB();b2DynamicTree.s_node_id=0;function std_iter_swap(array,a,b){const tmp=array[a];array[a]=array[b];array[b]=tmp;}function default_compare(a,b){return a<b;}function std_sort(array,first=0,len=array.length-first,cmp=default_compare){let left=first;const stack=[];let pos=0;for(;;){for(;left+1<len;len++){const pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(let right=left-1;;){while(cmp(array[++right],pivot)){}while(cmp(pivot,array[--len])){}if(right>=len){break;}std_iter_swap(array,right,len);}}if(pos===0){break;}left=len;len=stack[--pos];}return array;}class b2Pair{constructor(proxyA,proxyB){this.proxyA=proxyA;this.proxyB=proxyB;}}class b2BroadPhase{constructor(){this.m_tree=new b2DynamicTree();this.m_proxyCount=0;this.m_moveCount=0;this.m_moveBuffer=[];this.m_pairCount=0;this.m_pairBuffer=[];}CreateProxy(aabb,userData){const proxy=this.m_tree.CreateProxy(aabb,userData);++this.m_proxyCount;this.BufferMove(proxy);return proxy;}DestroyProxy(proxy){this.UnBufferMove(proxy);--this.m_proxyCount;this.m_tree.DestroyProxy(proxy);}MoveProxy(proxy,aabb,displacement){const buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy);}}TouchProxy(proxy){this.BufferMove(proxy);}GetProxyCount(){return this.m_proxyCount;}UpdatePairs(callback){this.m_pairCount=0;for(let i=0;i<this.m_moveCount;++i){const queryProxy=this.m_moveBuffer[i];if(queryProxy===null){continue;}const fatAABB=queryProxy.aabb;this.m_tree.Query(fatAABB,proxy=>{if(proxy.m_id===queryProxy.m_id){return true;}let proxyA;let proxyB;if(proxy.m_id<queryProxy.m_id){proxyA=proxy;proxyB=queryProxy;}else {proxyA=queryProxy;proxyB=proxy;}if(this.m_pairCount===this.m_pairBuffer.length){this.m_pairBuffer[this.m_pairCount]=new b2Pair(proxyA,proxyB);}else {const pair=this.m_pairBuffer[this.m_pairCount];pair.proxyA=proxyA;pair.proxyB=proxyB;}++this.m_pairCount;return true;});}this.m_moveCount=0;std_sort(this.m_pairBuffer,0,this.m_pairCount,b2PairLessThan);let i=0;while(i<this.m_pairCount){const primaryPair=this.m_pairBuffer[i];const userDataA=primaryPair.proxyA.userData;const userDataB=primaryPair.proxyB.userData;callback(userDataA,userDataB);++i;while(i<this.m_pairCount){const pair=this.m_pairBuffer[i];if(pair.proxyA.m_id!==primaryPair.proxyA.m_id||pair.proxyB.m_id!==primaryPair.proxyB.m_id){break;}++i;}}}Query(aabb,callback){this.m_tree.Query(aabb,callback);}QueryPoint(point,callback){this.m_tree.QueryPoint(point,callback);}RayCast(input,callback){this.m_tree.RayCast(input,callback);}GetTreeHeight(){return this.m_tree.GetHeight();}GetTreeBalance(){return this.m_tree.GetMaxBalance();}GetTreeQuality(){return this.m_tree.GetAreaRatio();}ShiftOrigin(newOrigin){this.m_tree.ShiftOrigin(newOrigin);}BufferMove(proxy){this.m_moveBuffer[this.m_moveCount]=proxy;++this.m_moveCount;}UnBufferMove(proxy){const i=this.m_moveBuffer.indexOf(proxy);this.m_moveBuffer[i]=null;}}function b2PairLessThan(pair1,pair2){if(pair1.proxyA.m_id<pair2.proxyA.m_id){return true;}if(pair1.proxyA.m_id===pair2.proxyA.m_id){return pair1.proxyB.m_id<pair2.proxyB.m_id;}return false;}exports.b2_toiTime=0;exports.b2_toiMaxTime=0;exports.b2_toiCalls=0;exports.b2_toiIters=0;exports.b2_toiMaxIters=0;exports.b2_toiRootIters=0;exports.b2_toiMaxRootIters=0;function b2_toi_reset(){exports.b2_toiTime=0;exports.b2_toiMaxTime=0;exports.b2_toiCalls=0;exports.b2_toiIters=0;exports.b2_toiMaxIters=0;exports.b2_toiRootIters=0;exports.b2_toiMaxRootIters=0;}const b2TimeOfImpact_s_xfA=new b2Transform();const b2TimeOfImpact_s_xfB=new b2Transform();const b2TimeOfImpact_s_pointA=new b2Vec2();const b2TimeOfImpact_s_pointB=new b2Vec2();const b2TimeOfImpact_s_normal=new b2Vec2();const b2TimeOfImpact_s_axisA=new b2Vec2();const b2TimeOfImpact_s_axisB=new b2Vec2();class b2TOIInput{constructor(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.sweepA=new b2Sweep();this.sweepB=new b2Sweep();this.tMax=0;}}(function(b2TOIOutputState){b2TOIOutputState[b2TOIOutputState["e_unknown"]=0]="e_unknown";b2TOIOutputState[b2TOIOutputState["e_failed"]=1]="e_failed";b2TOIOutputState[b2TOIOutputState["e_overlapped"]=2]="e_overlapped";b2TOIOutputState[b2TOIOutputState["e_touching"]=3]="e_touching";b2TOIOutputState[b2TOIOutputState["e_separated"]=4]="e_separated";})(exports.b2TOIOutputState||(exports.b2TOIOutputState={}));class b2TOIOutput{constructor(){this.state=exports.b2TOIOutputState.e_unknown;this.t=0;}}(function(b2SeparationFunctionType){b2SeparationFunctionType[b2SeparationFunctionType["e_unknown"]=-1]="e_unknown";b2SeparationFunctionType[b2SeparationFunctionType["e_points"]=0]="e_points";b2SeparationFunctionType[b2SeparationFunctionType["e_faceA"]=1]="e_faceA";b2SeparationFunctionType[b2SeparationFunctionType["e_faceB"]=2]="e_faceB";})(exports.b2SeparationFunctionType||(exports.b2SeparationFunctionType={}));class b2SeparationFunction{constructor(){this.m_sweepA=new b2Sweep();this.m_sweepB=new b2Sweep();this.m_type=exports.b2SeparationFunctionType.e_unknown;this.m_localPoint=new b2Vec2();this.m_axis=new b2Vec2();}Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1){this.m_proxyA=proxyA;this.m_proxyB=proxyB;const count=cache.count;this.m_sweepA.Copy(sweepA);this.m_sweepB.Copy(sweepB);const xfA=b2TimeOfImpact_s_xfA;const xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t1);this.m_sweepB.GetTransform(xfB,t1);if(count===1){this.m_type=exports.b2SeparationFunctionType.e_points;const localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);const localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);b2Vec2.SubVV(pointB,pointA,this.m_axis);const s=this.m_axis.Normalize();this.m_localPoint.SetZero();return s;}else if(cache.indexA[0]===cache.indexA[1]){this.m_type=exports.b2SeparationFunctionType.e_faceB;const localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);const localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointB2,localPointB1,b2Vec2.s_t0),this.m_axis).SelfNormalize();const normal=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointB1,localPointB2,this.m_localPoint);const pointB=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);const localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);let s=b2Vec2.DotVV(b2Vec2.SubVV(pointA,pointB,b2Vec2.s_t0),normal);if(s<0){this.m_axis.SelfNeg();s=-s;}return s;}else {this.m_type=exports.b2SeparationFunctionType.e_faceA;const localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);const localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointA2,localPointA1,b2Vec2.s_t0),this.m_axis).SelfNormalize();const normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointA1,localPointA2,this.m_localPoint);const pointA=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);const localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);let s=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),normal);if(s<0){this.m_axis.SelfNeg();s=-s;}return s;}}FindMinSeparation(indexA,indexB,t){const xfA=b2TimeOfImpact_s_xfA;const xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t);this.m_sweepB.GetTransform(xfB,t);switch(this.m_type){case exports.b2SeparationFunctionType.e_points:{const axisA=b2Rot.MulTRV(xfA.q,this.m_axis,b2TimeOfImpact_s_axisA);const axisB=b2Rot.MulTRV(xfB.q,b2Vec2.NegV(this.m_axis,b2Vec2.s_t0),b2TimeOfImpact_s_axisB);indexA[0]=this.m_proxyA.GetSupport(axisA);indexB[0]=this.m_proxyB.GetSupport(axisB);const localPointA=this.m_proxyA.GetVertex(indexA[0]);const localPointB=this.m_proxyB.GetVertex(indexB[0]);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports.b2SeparationFunctionType.e_faceA:{const normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);const pointA=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);const axisB=b2Rot.MulTRV(xfB.q,b2Vec2.NegV(normal,b2Vec2.s_t0),b2TimeOfImpact_s_axisB);indexA[0]=-1;indexB[0]=this.m_proxyB.GetSupport(axisB);const localPointB=this.m_proxyB.GetVertex(indexB[0]);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),normal);return separation;}case exports.b2SeparationFunctionType.e_faceB:{const normal=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);const pointB=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);const axisA=b2Rot.MulTRV(xfA.q,b2Vec2.NegV(normal,b2Vec2.s_t0),b2TimeOfImpact_s_axisA);indexB[0]=-1;indexA[0]=this.m_proxyA.GetSupport(axisA);const localPointA=this.m_proxyA.GetVertex(indexA[0]);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointA,pointB,b2Vec2.s_t0),normal);return separation;}default:indexA[0]=-1;indexB[0]=-1;return 0;}}Evaluate(indexA,indexB,t){const xfA=b2TimeOfImpact_s_xfA;const xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t);this.m_sweepB.GetTransform(xfB,t);switch(this.m_type){case exports.b2SeparationFunctionType.e_points:{const localPointA=this.m_proxyA.GetVertex(indexA);const localPointB=this.m_proxyB.GetVertex(indexB);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports.b2SeparationFunctionType.e_faceA:{const normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);const pointA=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);const localPointB=this.m_proxyB.GetVertex(indexB);const pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),normal);return separation;}case exports.b2SeparationFunctionType.e_faceB:{const normal=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);const pointB=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);const localPointA=this.m_proxyA.GetVertex(indexA);const pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);const separation=b2Vec2.DotVV(b2Vec2.SubVV(pointA,pointB,b2Vec2.s_t0),normal);return separation;}default:return 0;}}}const b2TimeOfImpact_s_timer=new b2Timer();const b2TimeOfImpact_s_cache=new b2SimplexCache();const b2TimeOfImpact_s_distanceInput=new b2DistanceInput();const b2TimeOfImpact_s_distanceOutput=new b2DistanceOutput();const b2TimeOfImpact_s_fcn=new b2SeparationFunction();const b2TimeOfImpact_s_indexA=[0];const b2TimeOfImpact_s_indexB=[0];const b2TimeOfImpact_s_sweepA=new b2Sweep();const b2TimeOfImpact_s_sweepB=new b2Sweep();function b2TimeOfImpact(output,input){const timer=b2TimeOfImpact_s_timer.Reset();++exports.b2_toiCalls;output.state=exports.b2TOIOutputState.e_unknown;output.t=input.tMax;const proxyA=input.proxyA;const proxyB=input.proxyB;const maxVertices=b2Max(b2_maxPolygonVertices,b2Max(proxyA.m_count,proxyB.m_count));const sweepA=b2TimeOfImpact_s_sweepA.Copy(input.sweepA);const sweepB=b2TimeOfImpact_s_sweepB.Copy(input.sweepB);sweepA.Normalize();sweepB.Normalize();const tMax=input.tMax;const totalRadius=proxyA.m_radius+proxyB.m_radius;const target=b2Max(b2_linearSlop,totalRadius-3*b2_linearSlop);const tolerance=0.25*b2_linearSlop;let t1=0;const k_maxIterations=20;let iter=0;const cache=b2TimeOfImpact_s_cache;cache.count=0;const distanceInput=b2TimeOfImpact_s_distanceInput;distanceInput.proxyA.Copy(input.proxyA);distanceInput.proxyB.Copy(input.proxyB);distanceInput.useRadii=false;for(;;){const xfA=b2TimeOfImpact_s_xfA;const xfB=b2TimeOfImpact_s_xfB;sweepA.GetTransform(xfA,t1);sweepB.GetTransform(xfB,t1);distanceInput.transformA.Copy(xfA);distanceInput.transformB.Copy(xfB);const distanceOutput=b2TimeOfImpact_s_distanceOutput;b2Distance(distanceOutput,cache,distanceInput);if(distanceOutput.distance<=0){output.state=exports.b2TOIOutputState.e_overlapped;output.t=0;break;}if(distanceOutput.distance<target+tolerance){output.state=exports.b2TOIOutputState.e_touching;output.t=t1;break;}const fcn=b2TimeOfImpact_s_fcn;fcn.Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1);let done=false;let t2=tMax;let pushBackIter=0;for(;;){const indexA=b2TimeOfImpact_s_indexA;const indexB=b2TimeOfImpact_s_indexB;let s2=fcn.FindMinSeparation(indexA,indexB,t2);if(s2>target+tolerance){output.state=exports.b2TOIOutputState.e_separated;output.t=tMax;done=true;break;}if(s2>target-tolerance){t1=t2;break;}let s1=fcn.Evaluate(indexA[0],indexB[0],t1);if(s1<target-tolerance){output.state=exports.b2TOIOutputState.e_failed;output.t=t1;done=true;break;}if(s1<=target+tolerance){output.state=exports.b2TOIOutputState.e_touching;output.t=t1;done=true;break;}let rootIterCount=0;let a1=t1;let a2=t2;for(;;){let t=0;if(rootIterCount&1){t=a1+(target-s1)*(a2-a1)/(s2-s1);}else {t=0.5*(a1+a2);}++rootIterCount;++exports.b2_toiRootIters;const s=fcn.Evaluate(indexA[0],indexB[0],t);if(b2Abs(s-target)<tolerance){t2=t;break;}if(s>target){a1=t;s1=s;}else {a2=t;s2=s;}if(rootIterCount===50){break;}}exports.b2_toiMaxRootIters=b2Max(exports.b2_toiMaxRootIters,rootIterCount);++pushBackIter;if(pushBackIter===maxVertices){break;}}++iter;++exports.b2_toiIters;if(done){break;}if(iter===k_maxIterations){output.state=exports.b2TOIOutputState.e_failed;output.t=t1;break;}}exports.b2_toiMaxIters=b2Max(exports.b2_toiMaxIters,iter);const time=timer.GetMilliseconds();exports.b2_toiMaxTime=b2Max(exports.b2_toiMaxTime,time);exports.b2_toiTime+=time;}const b2CollideCircles_s_pA=new b2Vec2();const b2CollideCircles_s_pB=new b2Vec2();function b2CollideCircles(manifold,circleA,xfA,circleB,xfB){manifold.pointCount=0;const pA=b2Transform.MulXV(xfA,circleA.m_p,b2CollideCircles_s_pA);const pB=b2Transform.MulXV(xfB,circleB.m_p,b2CollideCircles_s_pB);const distSqr=b2Vec2.DistanceSquaredVV(pA,pB);const radius=circleA.m_radius+circleB.m_radius;if(distSqr>radius*radius){return;}manifold.type=exports.b2ManifoldType.e_circles;manifold.localPoint.Copy(circleA.m_p);manifold.localNormal.SetZero();manifold.pointCount=1;manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}const b2CollidePolygonAndCircle_s_c=new b2Vec2();const b2CollidePolygonAndCircle_s_cLocal=new b2Vec2();const b2CollidePolygonAndCircle_s_faceCenter=new b2Vec2();function b2CollidePolygonAndCircle(manifold,polygonA,xfA,circleB,xfB){manifold.pointCount=0;const c=b2Transform.MulXV(xfB,circleB.m_p,b2CollidePolygonAndCircle_s_c);const cLocal=b2Transform.MulTXV(xfA,c,b2CollidePolygonAndCircle_s_cLocal);let normalIndex=0;let separation=-b2_maxFloat;const radius=polygonA.m_radius+circleB.m_radius;const vertexCount=polygonA.m_count;const vertices=polygonA.m_vertices;const normals=polygonA.m_normals;for(let i=0;i<vertexCount;++i){const s=b2Vec2.DotVV(normals[i],b2Vec2.SubVV(cLocal,vertices[i],b2Vec2.s_t0));if(s>radius){return;}if(s>separation){separation=s;normalIndex=i;}}const vertIndex1=normalIndex;const vertIndex2=(vertIndex1+1)%vertexCount;const v1=vertices[vertIndex1];const v2=vertices[vertIndex2];if(separation<b2_epsilon){manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;manifold.localNormal.Copy(normals[normalIndex]);b2Vec2.MidVV(v1,v2,manifold.localPoint);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;return;}const u1=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,v1,b2Vec2.s_t0),b2Vec2.SubVV(v2,v1,b2Vec2.s_t1));const u2=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,v2,b2Vec2.s_t0),b2Vec2.SubVV(v1,v2,b2Vec2.s_t1));if(u1<=0){if(b2Vec2.DistanceSquaredVV(cLocal,v1)>radius*radius){return;}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v1,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v1);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}else if(u2<=0){if(b2Vec2.DistanceSquaredVV(cLocal,v2)>radius*radius){return;}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v2,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v2);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}else {const faceCenter=b2Vec2.MidVV(v1,v2,b2CollidePolygonAndCircle_s_faceCenter);const separation=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,faceCenter,b2Vec2.s_t1),normals[vertIndex1]);if(separation>radius){return;}manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;manifold.localNormal.Copy(normals[vertIndex1]).SelfNormalize();manifold.localPoint.Copy(faceCenter);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}}const b2EdgeSeparation_s_normal1World=new b2Vec2();const b2EdgeSeparation_s_normal1=new b2Vec2();const b2EdgeSeparation_s_v1=new b2Vec2();const b2EdgeSeparation_s_v2=new b2Vec2();function b2EdgeSeparation(poly1,xf1,edge1,poly2,xf2){const vertices1=poly1.m_vertices;const normals1=poly1.m_normals;const count2=poly2.m_count;const vertices2=poly2.m_vertices;const normal1World=b2Rot.MulRV(xf1.q,normals1[edge1],b2EdgeSeparation_s_normal1World);const normal1=b2Rot.MulTRV(xf2.q,normal1World,b2EdgeSeparation_s_normal1);let index=0;let minDot=b2_maxFloat;for(let i=0;i<count2;++i){const dot=b2Vec2.DotVV(vertices2[i],normal1);if(dot<minDot){minDot=dot;index=i;}}const v1=b2Transform.MulXV(xf1,vertices1[edge1],b2EdgeSeparation_s_v1);const v2=b2Transform.MulXV(xf2,vertices2[index],b2EdgeSeparation_s_v2);const separation=b2Vec2.DotVV(b2Vec2.SubVV(v2,v1,b2Vec2.s_t0),normal1World);return separation;}const b2FindMaxSeparation_s_d=new b2Vec2();const b2FindMaxSeparation_s_dLocal1=new b2Vec2();function b2FindMaxSeparation(edgeIndex,poly1,xf1,poly2,xf2){const count1=poly1.m_count;const normals1=poly1.m_normals;const d=b2Vec2.SubVV(b2Transform.MulXV(xf2,poly2.m_centroid,b2Vec2.s_t0),b2Transform.MulXV(xf1,poly1.m_centroid,b2Vec2.s_t1),b2FindMaxSeparation_s_d);const dLocal1=b2Rot.MulTRV(xf1.q,d,b2FindMaxSeparation_s_dLocal1);let edge=0;let maxDot=-b2_maxFloat;for(let i=0;i<count1;++i){const dot=b2Vec2.DotVV(normals1[i],dLocal1);if(dot>maxDot){maxDot=dot;edge=i;}}let s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);const prevEdge=(edge+count1-1)%count1;const sPrev=b2EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);const nextEdge=(edge+1)%count1;const sNext=b2EdgeSeparation(poly1,xf1,nextEdge,poly2,xf2);let bestEdge=0;let bestSeparation=0;let increment=0;if(sPrev>s&&sPrev>sNext){increment=-1;bestEdge=prevEdge;bestSeparation=sPrev;}else if(sNext>s){increment=1;bestEdge=nextEdge;bestSeparation=sNext;}else {edgeIndex[0]=edge;return s;}while(true){if(increment===-1){edge=(bestEdge+count1-1)%count1;}else {edge=(bestEdge+1)%count1;}s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);if(s>bestSeparation){bestEdge=edge;bestSeparation=s;}else {break;}}edgeIndex[0]=bestEdge;return bestSeparation;}const b2FindIncidentEdge_s_normal1=new b2Vec2();function b2FindIncidentEdge(c,poly1,xf1,edge1,poly2,xf2){const normals1=poly1.m_normals;const count2=poly2.m_count;const vertices2=poly2.m_vertices;const normals2=poly2.m_normals;const normal1=b2Rot.MulTRV(xf2.q,b2Rot.MulRV(xf1.q,normals1[edge1],b2Vec2.s_t0),b2FindIncidentEdge_s_normal1);let index=0;let minDot=b2_maxFloat;for(let i=0;i<count2;++i){const dot=b2Vec2.DotVV(normal1,normals2[i]);if(dot<minDot){minDot=dot;index=i;}}const i1=index;const i2=(i1+1)%count2;const c0=c[0];b2Transform.MulXV(xf2,vertices2[i1],c0.v);const cf0=c0.id.cf;cf0.indexA=edge1;cf0.indexB=i1;cf0.typeA=exports.b2ContactFeatureType.e_face;cf0.typeB=exports.b2ContactFeatureType.e_vertex;const c1=c[1];b2Transform.MulXV(xf2,vertices2[i2],c1.v);const cf1=c1.id.cf;cf1.indexA=edge1;cf1.indexB=i2;cf1.typeA=exports.b2ContactFeatureType.e_face;cf1.typeB=exports.b2ContactFeatureType.e_vertex;}const b2CollidePolygons_s_incidentEdge=b2ClipVertex.MakeArray(2);const b2CollidePolygons_s_clipPoints1=b2ClipVertex.MakeArray(2);const b2CollidePolygons_s_clipPoints2=b2ClipVertex.MakeArray(2);const b2CollidePolygons_s_edgeA=[0];const b2CollidePolygons_s_edgeB=[0];const b2CollidePolygons_s_localTangent=new b2Vec2();const b2CollidePolygons_s_localNormal=new b2Vec2();const b2CollidePolygons_s_planePoint=new b2Vec2();const b2CollidePolygons_s_normal=new b2Vec2();const b2CollidePolygons_s_tangent=new b2Vec2();const b2CollidePolygons_s_ntangent=new b2Vec2();const b2CollidePolygons_s_v11=new b2Vec2();const b2CollidePolygons_s_v12=new b2Vec2();function b2CollidePolygons(manifold,polyA,xfA,polyB,xfB){manifold.pointCount=0;const totalRadius=polyA.m_radius+polyB.m_radius;const edgeA=b2CollidePolygons_s_edgeA;edgeA[0]=0;const separationA=b2FindMaxSeparation(edgeA,polyA,xfA,polyB,xfB);if(separationA>totalRadius){return;}const edgeB=b2CollidePolygons_s_edgeB;edgeB[0]=0;const separationB=b2FindMaxSeparation(edgeB,polyB,xfB,polyA,xfA);if(separationB>totalRadius){return;}let poly1;let poly2;let xf1,xf2;let edge1=0;let flip=0;const k_relativeTol=0.98;const k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB[0];manifold.type=exports.b2ManifoldType.e_faceB;flip=1;}else {poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA[0];manifold.type=exports.b2ManifoldType.e_faceA;flip=0;}const incidentEdge=b2CollidePolygons_s_incidentEdge;b2FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);const count1=poly1.m_count;const vertices1=poly1.m_vertices;const iv1=edge1;const iv2=(edge1+1)%count1;const local_v11=vertices1[iv1];const local_v12=vertices1[iv2];const localTangent=b2Vec2.SubVV(local_v12,local_v11,b2CollidePolygons_s_localTangent);localTangent.Normalize();const localNormal=b2Vec2.CrossVOne(localTangent,b2CollidePolygons_s_localNormal);const planePoint=b2Vec2.MidVV(local_v11,local_v12,b2CollidePolygons_s_planePoint);const tangent=b2Rot.MulRV(xf1.q,localTangent,b2CollidePolygons_s_tangent);const normal=b2Vec2.CrossVOne(tangent,b2CollidePolygons_s_normal);const v11=b2Transform.MulXV(xf1,local_v11,b2CollidePolygons_s_v11);const v12=b2Transform.MulXV(xf1,local_v12,b2CollidePolygons_s_v12);const frontOffset=b2Vec2.DotVV(normal,v11);const sideOffset1=-b2Vec2.DotVV(tangent,v11)+totalRadius;const sideOffset2=b2Vec2.DotVV(tangent,v12)+totalRadius;const clipPoints1=b2CollidePolygons_s_clipPoints1;const clipPoints2=b2CollidePolygons_s_clipPoints2;let np;const ntangent=b2Vec2.NegV(tangent,b2CollidePolygons_s_ntangent);np=b2ClipSegmentToLine(clipPoints1,incidentEdge,ntangent,sideOffset1,iv1);if(np<2){return;}np=b2ClipSegmentToLine(clipPoints2,clipPoints1,tangent,sideOffset2,iv2);if(np<2){return;}manifold.localNormal.Copy(localNormal);manifold.localPoint.Copy(planePoint);let pointCount=0;for(let i=0;i<b2_maxManifoldPoints;++i){const cv=clipPoints2[i];const separation=b2Vec2.DotVV(normal,cv.v)-frontOffset;if(separation<=totalRadius){const cp=manifold.points[pointCount];b2Transform.MulTXV(xf2,cv.v,cp.localPoint);cp.id.Copy(cv.id);if(flip){const cf=cp.id.cf;cp.id.cf.indexA=cf.indexB;cp.id.cf.indexB=cf.indexA;cp.id.cf.typeA=cf.typeB;cp.id.cf.typeB=cf.typeA;}++pointCount;}}manifold.pointCount=pointCount;}const b2CollideEdgeAndCircle_s_Q=new b2Vec2();const b2CollideEdgeAndCircle_s_e=new b2Vec2();const b2CollideEdgeAndCircle_s_d=new b2Vec2();const b2CollideEdgeAndCircle_s_e1=new b2Vec2();const b2CollideEdgeAndCircle_s_e2=new b2Vec2();const b2CollideEdgeAndCircle_s_P=new b2Vec2();const b2CollideEdgeAndCircle_s_n=new b2Vec2();const b2CollideEdgeAndCircle_s_id=new b2ContactID();function b2CollideEdgeAndCircle(manifold,edgeA,xfA,circleB,xfB){manifold.pointCount=0;const Q=b2Transform.MulTXV(xfA,b2Transform.MulXV(xfB,circleB.m_p,b2Vec2.s_t0),b2CollideEdgeAndCircle_s_Q);const A=edgeA.m_vertex1;const B=edgeA.m_vertex2;const e=b2Vec2.SubVV(B,A,b2CollideEdgeAndCircle_s_e);const u=b2Vec2.DotVV(e,b2Vec2.SubVV(B,Q,b2Vec2.s_t0));const v=b2Vec2.DotVV(e,b2Vec2.SubVV(Q,A,b2Vec2.s_t0));const radius=edgeA.m_radius+circleB.m_radius;const id=b2CollideEdgeAndCircle_s_id;id.cf.indexB=0;id.cf.typeB=exports.b2ContactFeatureType.e_vertex;if(v<=0){const P=A;const d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);const dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return;}if(edgeA.m_hasVertex0){const A1=edgeA.m_vertex0;const B1=A;const e1=b2Vec2.SubVV(B1,A1,b2CollideEdgeAndCircle_s_e1);const u1=b2Vec2.DotVV(e1,b2Vec2.SubVV(B1,Q,b2Vec2.s_t0));if(u1>0){return;}}id.cf.indexA=0;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(P);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return;}if(u<=0){const P=B;const d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);const dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return;}if(edgeA.m_hasVertex3){const B2=edgeA.m_vertex3;const A2=B;const e2=b2Vec2.SubVV(B2,A2,b2CollideEdgeAndCircle_s_e2);const v2=b2Vec2.DotVV(e2,b2Vec2.SubVV(Q,A2,b2Vec2.s_t0));if(v2>0){return;}}id.cf.indexA=1;id.cf.typeA=exports.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(P);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return;}const den=b2Vec2.DotVV(e,e);const P=b2CollideEdgeAndCircle_s_P;P.x=1/den*(u*A.x+v*B.x);P.y=1/den*(u*A.y+v*B.y);const d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);const dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return;}const n=b2CollideEdgeAndCircle_s_n.Set(-e.y,e.x);if(b2Vec2.DotVV(n,b2Vec2.SubVV(Q,A,b2Vec2.s_t0))<0){n.Set(-n.x,-n.y);}n.Normalize();id.cf.indexA=0;id.cf.typeA=exports.b2ContactFeatureType.e_face;manifold.pointCount=1;manifold.type=exports.b2ManifoldType.e_faceA;manifold.localNormal.Copy(n);manifold.localPoint.Copy(A);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);}var b2EPAxisType;(function(b2EPAxisType){b2EPAxisType[b2EPAxisType["e_unknown"]=0]="e_unknown";b2EPAxisType[b2EPAxisType["e_edgeA"]=1]="e_edgeA";b2EPAxisType[b2EPAxisType["e_edgeB"]=2]="e_edgeB";})(b2EPAxisType||(b2EPAxisType={}));class b2EPAxis{constructor(){this.type=b2EPAxisType.e_unknown;this.index=0;this.separation=0;}}class b2TempPolygon{constructor(){this.vertices=[];this.normals=[];this.count=0;}}class b2ReferenceFace{constructor(){this.i1=0;this.i2=0;this.v1=new b2Vec2();this.v2=new b2Vec2();this.normal=new b2Vec2();this.sideNormal1=new b2Vec2();this.sideOffset1=0;this.sideNormal2=new b2Vec2();this.sideOffset2=0;}}var b2EPColliderVertexType;(function(b2EPColliderVertexType){b2EPColliderVertexType[b2EPColliderVertexType["e_isolated"]=0]="e_isolated";b2EPColliderVertexType[b2EPColliderVertexType["e_concave"]=1]="e_concave";b2EPColliderVertexType[b2EPColliderVertexType["e_convex"]=2]="e_convex";})(b2EPColliderVertexType||(b2EPColliderVertexType={}));class b2EPCollider{constructor(){this.m_polygonB=new b2TempPolygon();this.m_xf=new b2Transform();this.m_centroidB=new b2Vec2();this.m_v0=new b2Vec2();this.m_v1=new b2Vec2();this.m_v2=new b2Vec2();this.m_v3=new b2Vec2();this.m_normal0=new b2Vec2();this.m_normal1=new b2Vec2();this.m_normal2=new b2Vec2();this.m_normal=new b2Vec2();this.m_type1=b2EPColliderVertexType.e_isolated;this.m_type2=b2EPColliderVertexType.e_isolated;this.m_lowerLimit=new b2Vec2();this.m_upperLimit=new b2Vec2();this.m_radius=0;this.m_front=false;}Collide(manifold,edgeA,xfA,polygonB,xfB){b2Transform.MulTXX(xfA,xfB,this.m_xf);b2Transform.MulXV(this.m_xf,polygonB.m_centroid,this.m_centroidB);this.m_v0.Copy(edgeA.m_vertex0);this.m_v1.Copy(edgeA.m_vertex1);this.m_v2.Copy(edgeA.m_vertex2);this.m_v3.Copy(edgeA.m_vertex3);const hasVertex0=edgeA.m_hasVertex0;const hasVertex3=edgeA.m_hasVertex3;const edge1=b2Vec2.SubVV(this.m_v2,this.m_v1,b2EPCollider.s_edge1);edge1.Normalize();this.m_normal1.Set(edge1.y,-edge1.x);const offset1=b2Vec2.DotVV(this.m_normal1,b2Vec2.SubVV(this.m_centroidB,this.m_v1,b2Vec2.s_t0));let offset0=0;let offset2=0;let convex1=false;let convex2=false;if(hasVertex0){const edge0=b2Vec2.SubVV(this.m_v1,this.m_v0,b2EPCollider.s_edge0);edge0.Normalize();this.m_normal0.Set(edge0.y,-edge0.x);convex1=b2Vec2.CrossVV(edge0,edge1)>=0;offset0=b2Vec2.DotVV(this.m_normal0,b2Vec2.SubVV(this.m_centroidB,this.m_v0,b2Vec2.s_t0));}if(hasVertex3){const edge2=b2Vec2.SubVV(this.m_v3,this.m_v2,b2EPCollider.s_edge2);edge2.Normalize();this.m_normal2.Set(edge2.y,-edge2.x);convex2=b2Vec2.CrossVV(edge1,edge2)>0;offset2=b2Vec2.DotVV(this.m_normal2,b2Vec2.SubVV(this.m_centroidB,this.m_v2,b2Vec2.s_t0));}if(hasVertex0&&hasVertex3){if(convex1&&convex2){this.m_front=offset0>=0||offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else if(convex1){this.m_front=offset0>=0||offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else if(convex2){this.m_front=offset2>=0||offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}else {this.m_front=offset0>=0&&offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}}else if(hasVertex0){if(convex1){this.m_front=offset0>=0||offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else {this.m_front=offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}}else if(hasVertex3){if(convex2){this.m_front=offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}}else {this.m_front=offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}}}else {this.m_front=offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1);}}this.m_polygonB.count=polygonB.m_count;for(let i=0;i<polygonB.m_count;++i){if(this.m_polygonB.vertices.length<=i){this.m_polygonB.vertices.push(new b2Vec2());}if(this.m_polygonB.normals.length<=i){this.m_polygonB.normals.push(new b2Vec2());}b2Transform.MulXV(this.m_xf,polygonB.m_vertices[i],this.m_polygonB.vertices[i]);b2Rot.MulRV(this.m_xf.q,polygonB.m_normals[i],this.m_polygonB.normals[i]);}this.m_radius=polygonB.m_radius+edgeA.m_radius;manifold.pointCount=0;const edgeAxis=this.ComputeEdgeSeparation(b2EPCollider.s_edgeAxis);if(edgeAxis.type===b2EPAxisType.e_unknown){return;}if(edgeAxis.separation>this.m_radius){return;}const polygonAxis=this.ComputePolygonSeparation(b2EPCollider.s_polygonAxis);if(polygonAxis.type!==b2EPAxisType.e_unknown&&polygonAxis.separation>this.m_radius){return;}const k_relativeTol=0.98;const k_absoluteTol=0.001;let primaryAxis;if(polygonAxis.type===b2EPAxisType.e_unknown){primaryAxis=edgeAxis;}else if(polygonAxis.separation>k_relativeTol*edgeAxis.separation+k_absoluteTol){primaryAxis=polygonAxis;}else {primaryAxis=edgeAxis;}const ie=b2EPCollider.s_ie;const rf=b2EPCollider.s_rf;if(primaryAxis.type===b2EPAxisType.e_edgeA){manifold.type=exports.b2ManifoldType.e_faceA;let bestIndex=0;let bestValue=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[0]);for(let i=1;i<this.m_polygonB.count;++i){const value=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[i]);if(value<bestValue){bestValue=value;bestIndex=i;}}const i1=bestIndex;const i2=(i1+1)%this.m_polygonB.count;const ie0=ie[0];ie0.v.Copy(this.m_polygonB.vertices[i1]);ie0.id.cf.indexA=0;ie0.id.cf.indexB=i1;ie0.id.cf.typeA=exports.b2ContactFeatureType.e_face;ie0.id.cf.typeB=exports.b2ContactFeatureType.e_vertex;const ie1=ie[1];ie1.v.Copy(this.m_polygonB.vertices[i2]);ie1.id.cf.indexA=0;ie1.id.cf.indexB=i2;ie1.id.cf.typeA=exports.b2ContactFeatureType.e_face;ie1.id.cf.typeB=exports.b2ContactFeatureType.e_vertex;if(this.m_front){rf.i1=0;rf.i2=1;rf.v1.Copy(this.m_v1);rf.v2.Copy(this.m_v2);rf.normal.Copy(this.m_normal1);}else {rf.i1=1;rf.i2=0;rf.v1.Copy(this.m_v2);rf.v2.Copy(this.m_v1);rf.normal.Copy(this.m_normal1).SelfNeg();}}else {manifold.type=exports.b2ManifoldType.e_faceB;const ie0=ie[0];ie0.v.Copy(this.m_v1);ie0.id.cf.indexA=0;ie0.id.cf.indexB=primaryAxis.index;ie0.id.cf.typeA=exports.b2ContactFeatureType.e_vertex;ie0.id.cf.typeB=exports.b2ContactFeatureType.e_face;const ie1=ie[1];ie1.v.Copy(this.m_v2);ie1.id.cf.indexA=0;ie1.id.cf.indexB=primaryAxis.index;ie1.id.cf.typeA=exports.b2ContactFeatureType.e_vertex;ie1.id.cf.typeB=exports.b2ContactFeatureType.e_face;rf.i1=primaryAxis.index;rf.i2=(rf.i1+1)%this.m_polygonB.count;rf.v1.Copy(this.m_polygonB.vertices[rf.i1]);rf.v2.Copy(this.m_polygonB.vertices[rf.i2]);rf.normal.Copy(this.m_polygonB.normals[rf.i1]);}rf.sideNormal1.Set(rf.normal.y,-rf.normal.x);rf.sideNormal2.Copy(rf.sideNormal1).SelfNeg();rf.sideOffset1=b2Vec2.DotVV(rf.sideNormal1,rf.v1);rf.sideOffset2=b2Vec2.DotVV(rf.sideNormal2,rf.v2);const clipPoints1=b2EPCollider.s_clipPoints1;const clipPoints2=b2EPCollider.s_clipPoints2;let np=0;np=b2ClipSegmentToLine(clipPoints1,ie,rf.sideNormal1,rf.sideOffset1,rf.i1);if(np<b2_maxManifoldPoints){return;}np=b2ClipSegmentToLine(clipPoints2,clipPoints1,rf.sideNormal2,rf.sideOffset2,rf.i2);if(np<b2_maxManifoldPoints){return;}if(primaryAxis.type===b2EPAxisType.e_edgeA){manifold.localNormal.Copy(rf.normal);manifold.localPoint.Copy(rf.v1);}else {manifold.localNormal.Copy(polygonB.m_normals[rf.i1]);manifold.localPoint.Copy(polygonB.m_vertices[rf.i1]);}let pointCount=0;for(let i=0;i<b2_maxManifoldPoints;++i){let separation;separation=b2Vec2.DotVV(rf.normal,b2Vec2.SubVV(clipPoints2[i].v,rf.v1,b2Vec2.s_t0));if(separation<=this.m_radius){const cp=manifold.points[pointCount];if(primaryAxis.type===b2EPAxisType.e_edgeA){b2Transform.MulTXV(this.m_xf,clipPoints2[i].v,cp.localPoint);cp.id.Copy(clipPoints2[i].id);}else {cp.localPoint.Copy(clipPoints2[i].v);cp.id.cf.typeA=clipPoints2[i].id.cf.typeB;cp.id.cf.typeB=clipPoints2[i].id.cf.typeA;cp.id.cf.indexA=clipPoints2[i].id.cf.indexB;cp.id.cf.indexB=clipPoints2[i].id.cf.indexA;}++pointCount;}}manifold.pointCount=pointCount;}ComputeEdgeSeparation(out){const axis=out;axis.type=b2EPAxisType.e_edgeA;axis.index=this.m_front?0:1;axis.separation=b2_maxFloat;for(let i=0;i<this.m_polygonB.count;++i){const s=b2Vec2.DotVV(this.m_normal,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v1,b2Vec2.s_t0));if(s<axis.separation){axis.separation=s;}}return axis;}ComputePolygonSeparation(out){const axis=out;axis.type=b2EPAxisType.e_unknown;axis.index=-1;axis.separation=-b2_maxFloat;const perp=b2EPCollider.s_perp.Set(-this.m_normal.y,this.m_normal.x);for(let i=0;i<this.m_polygonB.count;++i){const n=b2Vec2.NegV(this.m_polygonB.normals[i],b2EPCollider.s_n);const s1=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v1,b2Vec2.s_t0));const s2=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v2,b2Vec2.s_t0));const s=b2Min(s1,s2);if(s>this.m_radius){axis.type=b2EPAxisType.e_edgeB;axis.index=i;axis.separation=s;return axis;}if(b2Vec2.DotVV(n,perp)>=0){if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_upperLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue;}}else {if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_lowerLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue;}}if(s>axis.separation){axis.type=b2EPAxisType.e_edgeB;axis.index=i;axis.separation=s;}}return axis;}}b2EPCollider.s_edge1=new b2Vec2();b2EPCollider.s_edge0=new b2Vec2();b2EPCollider.s_edge2=new b2Vec2();b2EPCollider.s_ie=b2ClipVertex.MakeArray(2);b2EPCollider.s_rf=new b2ReferenceFace();b2EPCollider.s_clipPoints1=b2ClipVertex.MakeArray(2);b2EPCollider.s_clipPoints2=b2ClipVertex.MakeArray(2);b2EPCollider.s_edgeAxis=new b2EPAxis();b2EPCollider.s_polygonAxis=new b2EPAxis();b2EPCollider.s_n=new b2Vec2();b2EPCollider.s_perp=new b2Vec2();const b2CollideEdgeAndPolygon_s_collider=new b2EPCollider();function b2CollideEdgeAndPolygon(manifold,edgeA,xfA,polygonB,xfB){const collider=b2CollideEdgeAndPolygon_s_collider;collider.Collide(manifold,edgeA,xfA,polygonB,xfB);}class b2MassData{constructor(){this.mass=0;this.center=new b2Vec2(0,0);this.I=0;}}(function(b2ShapeType){b2ShapeType[b2ShapeType["e_unknown"]=-1]="e_unknown";b2ShapeType[b2ShapeType["e_circleShape"]=0]="e_circleShape";b2ShapeType[b2ShapeType["e_edgeShape"]=1]="e_edgeShape";b2ShapeType[b2ShapeType["e_polygonShape"]=2]="e_polygonShape";b2ShapeType[b2ShapeType["e_chainShape"]=3]="e_chainShape";b2ShapeType[b2ShapeType["e_shapeTypeCount"]=4]="e_shapeTypeCount";})(exports.b2ShapeType||(exports.b2ShapeType={}));class b2Shape{constructor(type,radius){this.m_type=exports.b2ShapeType.e_unknown;this.m_radius=0;this.m_type=type;this.m_radius=radius;}Copy(other){this.m_radius=other.m_radius;return this;}GetType(){return this.m_type;}}class b2CircleShape extends b2Shape{constructor(radius=0){super(exports.b2ShapeType.e_circleShape,radius);this.m_p=new b2Vec2();}Set(position,radius=this.m_radius){this.m_p.Copy(position);this.m_radius=radius;return this;}Clone(){return new b2CircleShape().Copy(this);}Copy(other){super.Copy(other);this.m_p.Copy(other.m_p);return this;}GetChildCount(){return 1;}TestPoint(transform,p){const center=b2Transform.MulXV(transform,this.m_p,b2CircleShape.TestPoint_s_center);const d=b2Vec2.SubVV(p,center,b2CircleShape.TestPoint_s_d);return b2Vec2.DotVV(d,d)<=b2Sq(this.m_radius);}ComputeDistance(xf,p,normal,childIndex){const center=b2Transform.MulXV(xf,this.m_p,b2CircleShape.ComputeDistance_s_center);b2Vec2.SubVV(p,center,normal);return normal.Normalize()-this.m_radius;}RayCast(output,input,transform,childIndex){const position=b2Transform.MulXV(transform,this.m_p,b2CircleShape.RayCast_s_position);const s=b2Vec2.SubVV(input.p1,position,b2CircleShape.RayCast_s_s);const b=b2Vec2.DotVV(s,s)-b2Sq(this.m_radius);const r=b2Vec2.SubVV(input.p2,input.p1,b2CircleShape.RayCast_s_r);const c=b2Vec2.DotVV(s,r);const rr=b2Vec2.DotVV(r,r);const sigma=c*c-rr*b;if(sigma<0||rr<b2_epsilon){return false;}let a=-(c+b2Sqrt(sigma));if(0<=a&&a<=input.maxFraction*rr){a/=rr;output.fraction=a;b2Vec2.AddVMulSV(s,a,r,output.normal).SelfNormalize();return true;}return false;}ComputeAABB(aabb,transform,childIndex){const p=b2Transform.MulXV(transform,this.m_p,b2CircleShape.ComputeAABB_s_p);aabb.lowerBound.Set(p.x-this.m_radius,p.y-this.m_radius);aabb.upperBound.Set(p.x+this.m_radius,p.y+this.m_radius);}ComputeMass(massData,density){const radius_sq=b2Sq(this.m_radius);massData.mass=density*b2_pi*radius_sq;massData.center.Copy(this.m_p);massData.I=massData.mass*(0.5*radius_sq+b2Vec2.DotVV(this.m_p,this.m_p));}SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_p);proxy.m_count=1;proxy.m_radius=this.m_radius;}ComputeSubmergedArea(normal,offset,xf,c){const p=b2Transform.MulXV(xf,this.m_p,new b2Vec2());const l=-(b2Vec2.DotVV(normal,p)-offset);if(l<-this.m_radius+b2_epsilon){return 0;}if(l>this.m_radius){c.Copy(p);return b2_pi*this.m_radius*this.m_radius;}const r2=this.m_radius*this.m_radius;const l2=l*l;const area=r2*(b2Asin(l/this.m_radius)+b2_pi/2)+l*b2Sqrt(r2-l2);const com=-2/3*b2Pow(r2-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;return area;}Dump(log){log("    const shape: b2CircleShape = new b2CircleShape();\n");log("    shape.m_radius = %.15f;\n",this.m_radius);log("    shape.m_p.Set(%.15f, %.15f);\n",this.m_p.x,this.m_p.y);}}b2CircleShape.TestPoint_s_center=new b2Vec2();b2CircleShape.TestPoint_s_d=new b2Vec2();b2CircleShape.ComputeDistance_s_center=new b2Vec2();b2CircleShape.RayCast_s_position=new b2Vec2();b2CircleShape.RayCast_s_s=new b2Vec2();b2CircleShape.RayCast_s_r=new b2Vec2();b2CircleShape.ComputeAABB_s_p=new b2Vec2();class b2PolygonShape extends b2Shape{constructor(){super(exports.b2ShapeType.e_polygonShape,b2_polygonRadius);this.m_centroid=new b2Vec2(0,0);this.m_vertices=[];this.m_normals=[];this.m_count=0;}Clone(){return new b2PolygonShape().Copy(this);}Copy(other){super.Copy(other);this.m_centroid.Copy(other.m_centroid);this.m_count=other.m_count;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(let i=0;i<this.m_count;++i){this.m_vertices[i].Copy(other.m_vertices[i]);this.m_normals[i].Copy(other.m_normals[i]);}return this;}GetChildCount(){return 1;}Set(...args){if(typeof args[0][0]==="number"){const vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._Set(index=>({x:vertices[index*2],y:vertices[index*2+1]}),vertices.length/2);}else {const vertices=args[0];const count=args[1]||vertices.length;return this._Set(index=>vertices[index],count);}}_Set(vertices,count){if(count<3){return this.SetAsBox(1,1);}let n=count;const ps=[];for(let i=0;i<n;++i){const v=vertices(i);let unique=true;for(let j=0;j<ps.length;++j){if(b2Vec2.DistanceSquaredVV(v,ps[j])<0.5*b2_linearSlop*(0.5*b2_linearSlop)){unique=false;break;}}if(unique){ps.push(v);}}n=ps.length;if(n<3){return this.SetAsBox(1.0,1.0);}let i0=0;let x0=ps[0].x;for(let i=1;i<n;++i){const x=ps[i].x;if(x>x0||x===x0&&ps[i].y<ps[i0].y){i0=i;x0=x;}}const hull=[];let m=0;let ih=i0;for(;;){hull[m]=ih;let ie=0;for(let j=1;j<n;++j){if(ie===ih){ie=j;continue;}const r=b2Vec2.SubVV(ps[ie],ps[hull[m]],b2PolygonShape.Set_s_r);const v=b2Vec2.SubVV(ps[j],ps[hull[m]],b2PolygonShape.Set_s_v);const c=b2Vec2.CrossVV(r,v);if(c<0){ie=j;}if(c===0&&v.LengthSquared()>r.LengthSquared()){ie=j;}}++m;ih=ie;if(ie===i0){break;}}this.m_count=m;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(let i=0;i<m;++i){this.m_vertices[i].Copy(ps[hull[i]]);}for(let i=0;i<m;++i){const vertexi1=this.m_vertices[i];const vertexi2=this.m_vertices[(i+1)%m];const edge=b2Vec2.SubVV(vertexi2,vertexi1,b2Vec2.s_t0);b2Vec2.CrossVOne(edge,this.m_normals[i]).SelfNormalize();}b2PolygonShape.ComputeCentroid(this.m_vertices,m,this.m_centroid);return this;}SetAsBox(hx,hy,center,angle=0){this.m_count=4;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);this.m_vertices[0].Set(-hx,-hy);this.m_vertices[1].Set(hx,-hy);this.m_vertices[2].Set(hx,hy);this.m_vertices[3].Set(-hx,hy);this.m_normals[0].Set(0,-1);this.m_normals[1].Set(1,0);this.m_normals[2].Set(0,1);this.m_normals[3].Set(-1,0);this.m_centroid.SetZero();if(center){this.m_centroid.Copy(center);const xf=new b2Transform();xf.SetPosition(center);xf.SetRotationAngle(angle);for(let i=0;i<this.m_count;++i){b2Transform.MulXV(xf,this.m_vertices[i],this.m_vertices[i]);b2Rot.MulRV(xf.q,this.m_normals[i],this.m_normals[i]);}}return this;}TestPoint(xf,p){const pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.TestPoint_s_pLocal);for(let i=0;i<this.m_count;++i){const dot=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(pLocal,this.m_vertices[i],b2Vec2.s_t0));if(dot>0){return false;}}return true;}ComputeDistance(xf,p,normal,childIndex){const pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.ComputeDistance_s_pLocal);let maxDistance=-b2_maxFloat;const normalForMaxDistance=b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal);for(let i=0;i<this.m_count;++i){const dot=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(pLocal,this.m_vertices[i],b2Vec2.s_t0));if(dot>maxDistance){maxDistance=dot;normalForMaxDistance.Copy(this.m_normals[i]);}}if(maxDistance>0){const minDistance=b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance);let minDistance2=maxDistance*maxDistance;for(let i=0;i<this.m_count;++i){const distance=b2Vec2.SubVV(pLocal,this.m_vertices[i],b2PolygonShape.ComputeDistance_s_distance);const distance2=distance.LengthSquared();if(minDistance2>distance2){minDistance.Copy(distance);minDistance2=distance2;}}b2Rot.MulRV(xf.q,minDistance,normal);normal.Normalize();return Math.sqrt(minDistance2);}else {b2Rot.MulRV(xf.q,normalForMaxDistance,normal);return maxDistance;}}RayCast(output,input,xf,childIndex){const p1=b2Transform.MulTXV(xf,input.p1,b2PolygonShape.RayCast_s_p1);const p2=b2Transform.MulTXV(xf,input.p2,b2PolygonShape.RayCast_s_p2);const d=b2Vec2.SubVV(p2,p1,b2PolygonShape.RayCast_s_d);let lower=0,upper=input.maxFraction;let index=-1;for(let i=0;i<this.m_count;++i){const numerator=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(this.m_vertices[i],p1,b2Vec2.s_t0));const denominator=b2Vec2.DotVV(this.m_normals[i],d);if(denominator===0){if(numerator<0){return false;}}else {if(denominator<0&&numerator<lower*denominator){lower=numerator/denominator;index=i;}else if(denominator>0&&numerator<upper*denominator){upper=numerator/denominator;}}if(upper<lower){return false;}}if(index>=0){output.fraction=lower;b2Rot.MulRV(xf.q,this.m_normals[index],output.normal);return true;}return false;}ComputeAABB(aabb,xf,childIndex){const lower=b2Transform.MulXV(xf,this.m_vertices[0],aabb.lowerBound);const upper=aabb.upperBound.Copy(lower);for(let i=0;i<this.m_count;++i){const v=b2Transform.MulXV(xf,this.m_vertices[i],b2PolygonShape.ComputeAABB_s_v);b2Vec2.MinV(v,lower,lower);b2Vec2.MaxV(v,upper,upper);}const r=this.m_radius;lower.SelfSubXY(r,r);upper.SelfAddXY(r,r);}ComputeMass(massData,density){const center=b2PolygonShape.ComputeMass_s_center.SetZero();let area=0;let I=0;const s=b2PolygonShape.ComputeMass_s_s.SetZero();for(let i=0;i<this.m_count;++i){s.SelfAdd(this.m_vertices[i]);}s.SelfMul(1/this.m_count);const k_inv3=1/3;for(let i=0;i<this.m_count;++i){const e1=b2Vec2.SubVV(this.m_vertices[i],s,b2PolygonShape.ComputeMass_s_e1);const e2=b2Vec2.SubVV(this.m_vertices[(i+1)%this.m_count],s,b2PolygonShape.ComputeMass_s_e2);const D=b2Vec2.CrossVV(e1,e2);const triangleArea=0.5*D;area+=triangleArea;center.SelfAdd(b2Vec2.MulSV(triangleArea*k_inv3,b2Vec2.AddVV(e1,e2,b2Vec2.s_t0),b2Vec2.s_t1));const ex1=e1.x;const ey1=e1.y;const ex2=e2.x;const ey2=e2.y;const intx2=ex1*ex1+ex2*ex1+ex2*ex2;const inty2=ey1*ey1+ey2*ey1+ey2*ey2;I+=0.25*k_inv3*D*(intx2+inty2);}massData.mass=density*area;center.SelfMul(1/area);b2Vec2.AddVV(center,s,massData.center);massData.I=density*I;massData.I+=massData.mass*(b2Vec2.DotVV(massData.center,massData.center)-b2Vec2.DotVV(center,center));}Validate(){for(let i=0;i<this.m_count;++i){const i1=i;const i2=(i+1)%this.m_count;const p=this.m_vertices[i1];const e=b2Vec2.SubVV(this.m_vertices[i2],p,b2PolygonShape.Validate_s_e);for(let j=0;j<this.m_count;++j){if(j===i1||j===i2){continue;}const v=b2Vec2.SubVV(this.m_vertices[j],p,b2PolygonShape.Validate_s_v);const c=b2Vec2.CrossVV(e,v);if(c<0){return false;}}}return true;}SetupDistanceProxy(proxy,index){proxy.m_vertices=this.m_vertices;proxy.m_count=this.m_count;proxy.m_radius=this.m_radius;}ComputeSubmergedArea(normal,offset,xf,c){const normalL=b2Rot.MulTRV(xf.q,normal,b2PolygonShape.ComputeSubmergedArea_s_normalL);const offsetL=offset-b2Vec2.DotVV(normal,xf.p);const depths=[];let diveCount=0;let intoIndex=-1;let outoIndex=-1;let lastSubmerged=false;for(let i=0;i<this.m_count;++i){depths[i]=b2Vec2.DotVV(normalL,this.m_vertices[i])-offsetL;const isSubmerged=depths[i]<-b2_epsilon;if(i>0){if(isSubmerged){if(!lastSubmerged){intoIndex=i-1;diveCount++;}}else {if(lastSubmerged){outoIndex=i-1;diveCount++;}}}lastSubmerged=isSubmerged;}switch(diveCount){case 0:if(lastSubmerged){const md=b2PolygonShape.ComputeSubmergedArea_s_md;this.ComputeMass(md,1);b2Transform.MulXV(xf,md.center,c);return md.mass;}else {return 0;}case 1:if(intoIndex===-1){intoIndex=this.m_count-1;}else {outoIndex=this.m_count-1;}break;}const intoIndex2=(intoIndex+1)%this.m_count;const outoIndex2=(outoIndex+1)%this.m_count;const intoLamdda=(0-depths[intoIndex])/(depths[intoIndex2]-depths[intoIndex]);const outoLamdda=(0-depths[outoIndex])/(depths[outoIndex2]-depths[outoIndex]);const intoVec=b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set(this.m_vertices[intoIndex].x*(1-intoLamdda)+this.m_vertices[intoIndex2].x*intoLamdda,this.m_vertices[intoIndex].y*(1-intoLamdda)+this.m_vertices[intoIndex2].y*intoLamdda);const outoVec=b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set(this.m_vertices[outoIndex].x*(1-outoLamdda)+this.m_vertices[outoIndex2].x*outoLamdda,this.m_vertices[outoIndex].y*(1-outoLamdda)+this.m_vertices[outoIndex2].y*outoLamdda);let area=0;const center=b2PolygonShape.ComputeSubmergedArea_s_center.SetZero();let p2=this.m_vertices[intoIndex2];let p3;let i=intoIndex2;while(i!==outoIndex2){i=(i+1)%this.m_count;if(i===outoIndex2){p3=outoVec;}else {p3=this.m_vertices[i];}const triangleArea=0.5*((p2.x-intoVec.x)*(p3.y-intoVec.y)-(p2.y-intoVec.y)*(p3.x-intoVec.x));area+=triangleArea;center.x+=triangleArea*(intoVec.x+p2.x+p3.x)/3;center.y+=triangleArea*(intoVec.y+p2.y+p3.y)/3;p2=p3;}center.SelfMul(1/area);b2Transform.MulXV(xf,center,c);return area;}Dump(log){log("    const shape: b2PolygonShape = new b2PolygonShape();\n");log("    const vs: b2Vec2[] = [];\n");for(let i=0;i<this.m_count;++i){log("    vs[%d] = new b2Vec2(%.15f, %.15f);\n",i,this.m_vertices[i].x,this.m_vertices[i].y);}log("    shape.Set(vs, %d);\n",this.m_count);}static ComputeCentroid(vs,count,out){const c=out;c.SetZero();let area=0;const pRef=b2PolygonShape.ComputeCentroid_s_pRef.SetZero();const inv3=1/3;for(let i=0;i<count;++i){const p1=pRef;const p2=vs[i];const p3=vs[(i+1)%count];const e1=b2Vec2.SubVV(p2,p1,b2PolygonShape.ComputeCentroid_s_e1);const e2=b2Vec2.SubVV(p3,p1,b2PolygonShape.ComputeCentroid_s_e2);const D=b2Vec2.CrossVV(e1,e2);const triangleArea=0.5*D;area+=triangleArea;c.x+=triangleArea*inv3*(p1.x+p2.x+p3.x);c.y+=triangleArea*inv3*(p1.y+p2.y+p3.y);}c.SelfMul(1/area);return c;}}b2PolygonShape.Set_s_r=new b2Vec2();b2PolygonShape.Set_s_v=new b2Vec2();b2PolygonShape.TestPoint_s_pLocal=new b2Vec2();b2PolygonShape.ComputeDistance_s_pLocal=new b2Vec2();b2PolygonShape.ComputeDistance_s_normalForMaxDistance=new b2Vec2();b2PolygonShape.ComputeDistance_s_minDistance=new b2Vec2();b2PolygonShape.ComputeDistance_s_distance=new b2Vec2();b2PolygonShape.RayCast_s_p1=new b2Vec2();b2PolygonShape.RayCast_s_p2=new b2Vec2();b2PolygonShape.RayCast_s_d=new b2Vec2();b2PolygonShape.ComputeAABB_s_v=new b2Vec2();b2PolygonShape.ComputeMass_s_center=new b2Vec2();b2PolygonShape.ComputeMass_s_s=new b2Vec2();b2PolygonShape.ComputeMass_s_e1=new b2Vec2();b2PolygonShape.ComputeMass_s_e2=new b2Vec2();b2PolygonShape.Validate_s_e=new b2Vec2();b2PolygonShape.Validate_s_v=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_normalL=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_md=new b2MassData();b2PolygonShape.ComputeSubmergedArea_s_intoVec=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_outoVec=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_center=new b2Vec2();b2PolygonShape.ComputeCentroid_s_pRef=new b2Vec2();b2PolygonShape.ComputeCentroid_s_e1=new b2Vec2();b2PolygonShape.ComputeCentroid_s_e2=new b2Vec2();class b2EdgeShape extends b2Shape{constructor(){super(exports.b2ShapeType.e_edgeShape,b2_polygonRadius);this.m_vertex1=new b2Vec2();this.m_vertex2=new b2Vec2();this.m_vertex0=new b2Vec2();this.m_vertex3=new b2Vec2();this.m_hasVertex0=false;this.m_hasVertex3=false;}Set(v1,v2){this.m_vertex1.Copy(v1);this.m_vertex2.Copy(v2);this.m_hasVertex0=false;this.m_hasVertex3=false;return this;}Clone(){return new b2EdgeShape().Copy(this);}Copy(other){super.Copy(other);this.m_vertex1.Copy(other.m_vertex1);this.m_vertex2.Copy(other.m_vertex2);this.m_vertex0.Copy(other.m_vertex0);this.m_vertex3.Copy(other.m_vertex3);this.m_hasVertex0=other.m_hasVertex0;this.m_hasVertex3=other.m_hasVertex3;return this;}GetChildCount(){return 1;}TestPoint(xf,p){return false;}ComputeDistance(xf,p,normal,childIndex){const v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeDistance_s_v1);const v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeDistance_s_v2);const d=b2Vec2.SubVV(p,v1,b2EdgeShape.ComputeDistance_s_d);const s=b2Vec2.SubVV(v2,v1,b2EdgeShape.ComputeDistance_s_s);const ds=b2Vec2.DotVV(d,s);if(ds>0){const s2=b2Vec2.DotVV(s,s);if(ds>s2){b2Vec2.SubVV(p,v2,d);}else {d.SelfMulSub(ds/s2,s);}}normal.Copy(d);return normal.Normalize();}RayCast(output,input,xf,childIndex){const p1=b2Transform.MulTXV(xf,input.p1,b2EdgeShape.RayCast_s_p1);const p2=b2Transform.MulTXV(xf,input.p2,b2EdgeShape.RayCast_s_p2);const d=b2Vec2.SubVV(p2,p1,b2EdgeShape.RayCast_s_d);const v1=this.m_vertex1;const v2=this.m_vertex2;const e=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_e);const normal=output.normal.Set(e.y,-e.x).SelfNormalize();const numerator=b2Vec2.DotVV(normal,b2Vec2.SubVV(v1,p1,b2Vec2.s_t0));const denominator=b2Vec2.DotVV(normal,d);if(denominator===0){return false;}const t=numerator/denominator;if(t<0||input.maxFraction<t){return false;}const q=b2Vec2.AddVMulSV(p1,t,d,b2EdgeShape.RayCast_s_q);const r=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_r);const rr=b2Vec2.DotVV(r,r);if(rr===0){return false;}const s=b2Vec2.DotVV(b2Vec2.SubVV(q,v1,b2Vec2.s_t0),r)/rr;if(s<0||1<s){return false;}output.fraction=t;b2Rot.MulRV(xf.q,output.normal,output.normal);if(numerator>0){output.normal.SelfNeg();}return true;}ComputeAABB(aabb,xf,childIndex){const v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeAABB_s_v1);const v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);const r=this.m_radius;aabb.lowerBound.SelfSubXY(r,r);aabb.upperBound.SelfAddXY(r,r);}ComputeMass(massData,density){massData.mass=0;b2Vec2.MidVV(this.m_vertex1,this.m_vertex2,massData.center);massData.I=0;}SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_vertex1);proxy.m_vertices[1].Copy(this.m_vertex2);proxy.m_count=2;proxy.m_radius=this.m_radius;}ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;}Dump(log){log("    const shape: b2EdgeShape = new b2EdgeShape();\n");log("    shape.m_radius = %.15f;\n",this.m_radius);log("    shape.m_vertex0.Set(%.15f, %.15f);\n",this.m_vertex0.x,this.m_vertex0.y);log("    shape.m_vertex1.Set(%.15f, %.15f);\n",this.m_vertex1.x,this.m_vertex1.y);log("    shape.m_vertex2.Set(%.15f, %.15f);\n",this.m_vertex2.x,this.m_vertex2.y);log("    shape.m_vertex3.Set(%.15f, %.15f);\n",this.m_vertex3.x,this.m_vertex3.y);log("    shape.m_hasVertex0 = %s;\n",this.m_hasVertex0);log("    shape.m_hasVertex3 = %s;\n",this.m_hasVertex3);}}b2EdgeShape.ComputeDistance_s_v1=new b2Vec2();b2EdgeShape.ComputeDistance_s_v2=new b2Vec2();b2EdgeShape.ComputeDistance_s_d=new b2Vec2();b2EdgeShape.ComputeDistance_s_s=new b2Vec2();b2EdgeShape.RayCast_s_p1=new b2Vec2();b2EdgeShape.RayCast_s_p2=new b2Vec2();b2EdgeShape.RayCast_s_d=new b2Vec2();b2EdgeShape.RayCast_s_e=new b2Vec2();b2EdgeShape.RayCast_s_q=new b2Vec2();b2EdgeShape.RayCast_s_r=new b2Vec2();b2EdgeShape.ComputeAABB_s_v1=new b2Vec2();b2EdgeShape.ComputeAABB_s_v2=new b2Vec2();class b2ChainShape extends b2Shape{constructor(){super(exports.b2ShapeType.e_chainShape,b2_polygonRadius);this.m_vertices=[];this.m_count=0;this.m_prevVertex=new b2Vec2();this.m_nextVertex=new b2Vec2();this.m_hasPrevVertex=false;this.m_hasNextVertex=false;}CreateLoop(...args){if(typeof args[0][0]==="number"){const vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateLoop(index=>({x:vertices[index*2],y:vertices[index*2+1]}),vertices.length/2);}else {const vertices=args[0];const count=args[1]||vertices.length;return this._CreateLoop(index=>vertices[index],count);}}_CreateLoop(vertices,count){if(count<3){return this;}this.m_count=count+1;this.m_vertices=b2Vec2.MakeArray(this.m_count);for(let i=0;i<count;++i){this.m_vertices[i].Copy(vertices(i));}this.m_vertices[count].Copy(this.m_vertices[0]);this.m_prevVertex.Copy(this.m_vertices[this.m_count-2]);this.m_nextVertex.Copy(this.m_vertices[1]);this.m_hasPrevVertex=true;this.m_hasNextVertex=true;return this;}CreateChain(...args){if(typeof args[0][0]==="number"){const vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateChain(index=>({x:vertices[index*2],y:vertices[index*2+1]}),vertices.length/2);}else {const vertices=args[0];const count=args[1]||vertices.length;return this._CreateChain(index=>vertices[index],count);}}_CreateChain(vertices,count){this.m_count=count;this.m_vertices=b2Vec2.MakeArray(count);for(let i=0;i<count;++i){this.m_vertices[i].Copy(vertices(i));}this.m_hasPrevVertex=false;this.m_hasNextVertex=false;this.m_prevVertex.SetZero();this.m_nextVertex.SetZero();return this;}SetPrevVertex(prevVertex){this.m_prevVertex.Copy(prevVertex);this.m_hasPrevVertex=true;return this;}SetNextVertex(nextVertex){this.m_nextVertex.Copy(nextVertex);this.m_hasNextVertex=true;return this;}Clone(){return new b2ChainShape().Copy(this);}Copy(other){super.Copy(other);this._CreateChain(index=>other.m_vertices[index],other.m_count);this.m_prevVertex.Copy(other.m_prevVertex);this.m_nextVertex.Copy(other.m_nextVertex);this.m_hasPrevVertex=other.m_hasPrevVertex;this.m_hasNextVertex=other.m_hasNextVertex;return this;}GetChildCount(){return this.m_count-1;}GetChildEdge(edge,index){edge.m_radius=this.m_radius;edge.m_vertex1.Copy(this.m_vertices[index]);edge.m_vertex2.Copy(this.m_vertices[index+1]);if(index>0){edge.m_vertex0.Copy(this.m_vertices[index-1]);edge.m_hasVertex0=true;}else {edge.m_vertex0.Copy(this.m_prevVertex);edge.m_hasVertex0=this.m_hasPrevVertex;}if(index<this.m_count-2){edge.m_vertex3.Copy(this.m_vertices[index+2]);edge.m_hasVertex3=true;}else {edge.m_vertex3.Copy(this.m_nextVertex);edge.m_hasVertex3=this.m_hasNextVertex;}}TestPoint(xf,p){return false;}ComputeDistance(xf,p,normal,childIndex){const edge=b2ChainShape.ComputeDistance_s_edgeShape;this.GetChildEdge(edge,childIndex);return edge.ComputeDistance(xf,p,normal,0);}RayCast(output,input,xf,childIndex){const edgeShape=b2ChainShape.RayCast_s_edgeShape;edgeShape.m_vertex1.Copy(this.m_vertices[childIndex]);edgeShape.m_vertex2.Copy(this.m_vertices[(childIndex+1)%this.m_count]);return edgeShape.RayCast(output,input,xf,0);}ComputeAABB(aabb,xf,childIndex){const vertexi1=this.m_vertices[childIndex];const vertexi2=this.m_vertices[(childIndex+1)%this.m_count];const v1=b2Transform.MulXV(xf,vertexi1,b2ChainShape.ComputeAABB_s_v1);const v2=b2Transform.MulXV(xf,vertexi2,b2ChainShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);}ComputeMass(massData,density){massData.mass=0;massData.center.SetZero();massData.I=0;}SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_vertices[index]);if(index+1<this.m_count){proxy.m_vertices[1].Copy(this.m_vertices[index+1]);}else {proxy.m_vertices[1].Copy(this.m_vertices[0]);}proxy.m_count=2;proxy.m_radius=this.m_radius;}ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;}Dump(log){log("    const shape: b2ChainShape = new b2ChainShape();\n");log("    const vs: b2Vec2[] = [];\n");for(let i=0;i<this.m_count;++i){log("    vs[%d] = new bVec2(%.15f, %.15f);\n",i,this.m_vertices[i].x,this.m_vertices[i].y);}log("    shape.CreateChain(vs, %d);\n",this.m_count);log("    shape.m_prevVertex.Set(%.15f, %.15f);\n",this.m_prevVertex.x,this.m_prevVertex.y);log("    shape.m_nextVertex.Set(%.15f, %.15f);\n",this.m_nextVertex.x,this.m_nextVertex.y);log("    shape.m_hasPrevVertex = %s;\n",this.m_hasPrevVertex?"true":"false");log("    shape.m_hasNextVertex = %s;\n",this.m_hasNextVertex?"true":"false");}}b2ChainShape.ComputeDistance_s_edgeShape=new b2EdgeShape();b2ChainShape.RayCast_s_edgeShape=new b2EdgeShape();b2ChainShape.ComputeAABB_s_v1=new b2Vec2();b2ChainShape.ComputeAABB_s_v2=new b2Vec2();class b2Filter{constructor(){this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;}Clone(){return new b2Filter().Copy(this);}Copy(other){this.categoryBits=other.categoryBits;this.maskBits=other.maskBits;this.groupIndex=other.groupIndex||0;return this;}}b2Filter.DEFAULT=new b2Filter();class b2FixtureDef{constructor(){this.userData=null;this.friction=0.2;this.restitution=0;this.density=0;this.isSensor=false;this.filter=new b2Filter();}}class b2FixtureProxy{constructor(fixture,childIndex){this.aabb=new b2AABB();this.childIndex=0;this.fixture=fixture;this.childIndex=childIndex;this.fixture.m_shape.ComputeAABB(this.aabb,this.fixture.m_body.GetTransform(),childIndex);this.treeNode=this.fixture.m_body.m_world.m_contactManager.m_broadPhase.CreateProxy(this.aabb,this);}Reset(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.DestroyProxy(this.treeNode);}Touch(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.TouchProxy(this.treeNode);}Synchronize(transform1,transform2,displacement){if(transform1===transform2){this.fixture.m_shape.ComputeAABB(this.aabb,transform1,this.childIndex);this.fixture.m_body.m_world.m_contactManager.m_broadPhase.MoveProxy(this.treeNode,this.aabb,displacement);}else {const aabb1=b2FixtureProxy.Synchronize_s_aabb1;const aabb2=b2FixtureProxy.Synchronize_s_aabb2;this.fixture.m_shape.ComputeAABB(aabb1,transform1,this.childIndex);this.fixture.m_shape.ComputeAABB(aabb2,transform2,this.childIndex);this.aabb.Combine2(aabb1,aabb2);this.fixture.m_body.m_world.m_contactManager.m_broadPhase.MoveProxy(this.treeNode,this.aabb,displacement);}}}b2FixtureProxy.Synchronize_s_aabb1=new b2AABB();b2FixtureProxy.Synchronize_s_aabb2=new b2AABB();class b2Fixture{constructor(body,def){this.m_density=0;this.m_next=null;this.m_friction=0;this.m_restitution=0;this.m_proxies=[];this.m_filter=new b2Filter();this.m_isSensor=false;this.m_userData=null;this.m_body=body;this.m_shape=def.shape.Clone();this.m_userData=b2Maybe(def.userData,null);this.m_friction=b2Maybe(def.friction,0.2);this.m_restitution=b2Maybe(def.restitution,0);this.m_filter.Copy(b2Maybe(def.filter,b2Filter.DEFAULT));this.m_isSensor=b2Maybe(def.isSensor,false);this.m_density=b2Maybe(def.density,0);}get m_proxyCount(){return this.m_proxies.length;}Reset(){}GetType(){return this.m_shape.GetType();}GetShape(){return this.m_shape;}SetSensor(sensor){if(sensor!==this.m_isSensor){this.m_body.SetAwake(true);this.m_isSensor=sensor;}}IsSensor(){return this.m_isSensor;}SetFilterData(filter){this.m_filter.Copy(filter);this.Refilter();}GetFilterData(){return this.m_filter;}Refilter(){let edge=this.m_body.GetContactList();while(edge){const contact=edge.contact;const fixtureA=contact.GetFixtureA();const fixtureB=contact.GetFixtureB();if(fixtureA===this||fixtureB===this){contact.FlagForFiltering();}edge=edge.next;}this.TouchProxies();}GetBody(){return this.m_body;}GetNext(){return this.m_next;}GetUserData(){return this.m_userData;}SetUserData(data){this.m_userData=data;}TestPoint(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p);}ComputeDistance(p,normal,childIndex){return this.m_shape.ComputeDistance(this.m_body.GetTransform(),p,normal,childIndex);}RayCast(output,input,childIndex){return this.m_shape.RayCast(output,input,this.m_body.GetTransform(),childIndex);}GetMassData(massData=new b2MassData()){this.m_shape.ComputeMass(massData,this.m_density);return massData;}SetDensity(density){this.m_density=density;}GetDensity(){return this.m_density;}GetFriction(){return this.m_friction;}SetFriction(friction){this.m_friction=friction;}GetRestitution(){return this.m_restitution;}SetRestitution(restitution){this.m_restitution=restitution;}GetAABB(childIndex){return this.m_proxies[childIndex].aabb;}Dump(log,bodyIndex){log("    const fd: b2FixtureDef = new b2FixtureDef();\n");log("    fd.friction = %.15f;\n",this.m_friction);log("    fd.restitution = %.15f;\n",this.m_restitution);log("    fd.density = %.15f;\n",this.m_density);log("    fd.isSensor = %s;\n",this.m_isSensor?"true":"false");log("    fd.filter.categoryBits = %d;\n",this.m_filter.categoryBits);log("    fd.filter.maskBits = %d;\n",this.m_filter.maskBits);log("    fd.filter.groupIndex = %d;\n",this.m_filter.groupIndex);this.m_shape.Dump(log);log("\n");log("    fd.shape = shape;\n");log("\n");log("    bodies[%d].CreateFixture(fd);\n",bodyIndex);}CreateProxies(){if(this.m_proxies.length!==0){throw new Error();}for(let i=0;i<this.m_shape.GetChildCount();++i){this.m_proxies[i]=new b2FixtureProxy(this,i);}}DestroyProxies(){for(const proxy of this.m_proxies){proxy.Reset();}this.m_proxies.length=0;}TouchProxies(){for(const proxy of this.m_proxies){proxy.Touch();}}SynchronizeProxies(transform1,transform2,displacement){for(const proxy of this.m_proxies){proxy.Synchronize(transform1,transform2,displacement);}}}(function(b2BodyType){b2BodyType[b2BodyType["b2_unknown"]=-1]="b2_unknown";b2BodyType[b2BodyType["b2_staticBody"]=0]="b2_staticBody";b2BodyType[b2BodyType["b2_kinematicBody"]=1]="b2_kinematicBody";b2BodyType[b2BodyType["b2_dynamicBody"]=2]="b2_dynamicBody";})(exports.b2BodyType||(exports.b2BodyType={}));class b2BodyDef{constructor(){this.type=exports.b2BodyType.b2_staticBody;this.position=new b2Vec2(0,0);this.angle=0;this.linearVelocity=new b2Vec2(0,0);this.angularVelocity=0;this.linearDamping=0;this.angularDamping=0;this.allowSleep=true;this.awake=true;this.fixedRotation=false;this.bullet=false;this.active=true;this.userData=null;this.gravityScale=1;}}class b2Body{constructor(bd,world){this.m_type=exports.b2BodyType.b2_staticBody;this.m_islandFlag=false;this.m_awakeFlag=false;this.m_autoSleepFlag=false;this.m_bulletFlag=false;this.m_fixedRotationFlag=false;this.m_activeFlag=false;this.m_toiFlag=false;this.m_islandIndex=0;this.m_xf=new b2Transform();this.m_xf0=new b2Transform();this.m_sweep=new b2Sweep();this.m_linearVelocity=new b2Vec2();this.m_angularVelocity=0;this.m_force=new b2Vec2();this.m_torque=0;this.m_prev=null;this.m_next=null;this.m_fixtureList=null;this.m_fixtureCount=0;this.m_jointList=null;this.m_contactList=null;this.m_mass=1;this.m_invMass=1;this.m_I=0;this.m_invI=0;this.m_linearDamping=0;this.m_angularDamping=0;this.m_gravityScale=1;this.m_sleepTime=0;this.m_userData=null;this.m_controllerList=null;this.m_controllerCount=0;this.m_bulletFlag=b2Maybe(bd.bullet,false);this.m_fixedRotationFlag=b2Maybe(bd.fixedRotation,false);this.m_autoSleepFlag=b2Maybe(bd.allowSleep,true);this.m_awakeFlag=b2Maybe(bd.awake,true);this.m_activeFlag=b2Maybe(bd.active,true);this.m_world=world;this.m_xf.p.Copy(b2Maybe(bd.position,b2Vec2.ZERO));this.m_xf.q.SetAngle(b2Maybe(bd.angle,0));this.m_xf0.Copy(this.m_xf);this.m_sweep.localCenter.SetZero();this.m_sweep.c0.Copy(this.m_xf.p);this.m_sweep.c.Copy(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a=this.m_xf.q.GetAngle();this.m_sweep.alpha0=0;this.m_linearVelocity.Copy(b2Maybe(bd.linearVelocity,b2Vec2.ZERO));this.m_angularVelocity=b2Maybe(bd.angularVelocity,0);this.m_linearDamping=b2Maybe(bd.linearDamping,0);this.m_angularDamping=b2Maybe(bd.angularDamping,0);this.m_gravityScale=b2Maybe(bd.gravityScale,1);this.m_force.SetZero();this.m_torque=0;this.m_sleepTime=0;this.m_type=b2Maybe(bd.type,exports.b2BodyType.b2_staticBody);if(bd.type===exports.b2BodyType.b2_dynamicBody){this.m_mass=1;this.m_invMass=1;}else {this.m_mass=0;this.m_invMass=0;}this.m_I=0;this.m_invI=0;this.m_userData=bd.userData;this.m_fixtureList=null;this.m_fixtureCount=0;this.m_controllerList=null;this.m_controllerCount=0;}CreateFixture(a,b=0){if(a instanceof b2Shape){return this.CreateFixtureShapeDensity(a,b);}else {return this.CreateFixtureDef(a);}}CreateFixtureDef(def){if(this.m_world.IsLocked()){throw new Error();}const fixture=new b2Fixture(this,def);if(this.m_activeFlag){fixture.CreateProxies();}fixture.m_next=this.m_fixtureList;this.m_fixtureList=fixture;++this.m_fixtureCount;if(fixture.m_density>0){this.ResetMassData();}this.m_world.m_newFixture=true;return fixture;}CreateFixtureShapeDensity(shape,density=0){const def=b2Body.CreateFixtureShapeDensity_s_def;def.shape=shape;def.density=density;return this.CreateFixtureDef(def);}DestroyFixture(fixture){if(this.m_world.IsLocked()){throw new Error();}let node=this.m_fixtureList;let ppF=null;while(node!==null){if(node===fixture){if(ppF){ppF.m_next=fixture.m_next;}else {this.m_fixtureList=fixture.m_next;}break;}ppF=node;node=node.m_next;}let edge=this.m_contactList;while(edge){const c=edge.contact;edge=edge.next;const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();if(fixture===fixtureA||fixture===fixtureB){this.m_world.m_contactManager.Destroy(c);}}if(this.m_activeFlag){fixture.DestroyProxies();}fixture.m_next=null;fixture.Reset();--this.m_fixtureCount;this.ResetMassData();}SetTransformVec(position,angle){this.SetTransformXY(position.x,position.y,angle);}SetTransformXY(x,y,angle){if(this.m_world.IsLocked()){throw new Error();}this.m_xf.q.SetAngle(angle);this.m_xf.p.Set(x,y);this.m_xf0.Copy(this.m_xf);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.a=angle;this.m_sweep.c0.Copy(this.m_sweep.c);this.m_sweep.a0=angle;for(let f=this.m_fixtureList;f;f=f.m_next){f.SynchronizeProxies(this.m_xf,this.m_xf,b2Vec2.ZERO);}this.m_world.m_contactManager.FindNewContacts();}SetTransform(xf){this.SetTransformVec(xf.p,xf.GetAngle());}GetTransform(){return this.m_xf;}GetPosition(){return this.m_xf.p;}SetPosition(position){this.SetTransformVec(position,this.GetAngle());}SetPositionXY(x,y){this.SetTransformXY(x,y,this.GetAngle());}GetAngle(){return this.m_sweep.a;}SetAngle(angle){this.SetTransformVec(this.GetPosition(),angle);}GetWorldCenter(){return this.m_sweep.c;}GetLocalCenter(){return this.m_sweep.localCenter;}SetLinearVelocity(v){if(this.m_type===exports.b2BodyType.b2_staticBody){return;}if(b2Vec2.DotVV(v,v)>0){this.SetAwake(true);}this.m_linearVelocity.Copy(v);}GetLinearVelocity(){return this.m_linearVelocity;}SetAngularVelocity(w){if(this.m_type===exports.b2BodyType.b2_staticBody){return;}if(w*w>0){this.SetAwake(true);}this.m_angularVelocity=w;}GetAngularVelocity(){return this.m_angularVelocity;}GetDefinition(bd){bd.type=this.GetType();bd.allowSleep=this.m_autoSleepFlag;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.gravityScale=this.m_gravityScale;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=this.m_fixedRotationFlag;bd.bullet=this.m_bulletFlag;bd.awake=this.m_awakeFlag;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.Copy(this.GetLinearVelocity());bd.position.Copy(this.GetPosition());bd.userData=this.GetUserData();return bd;}ApplyForce(force,point,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_force.x+=force.x;this.m_force.y+=force.y;this.m_torque+=(point.x-this.m_sweep.c.x)*force.y-(point.y-this.m_sweep.c.y)*force.x;}}ApplyForceToCenter(force,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_force.x+=force.x;this.m_force.y+=force.y;}}ApplyTorque(torque,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_torque+=torque;}}ApplyLinearImpulse(impulse,point,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y;this.m_angularVelocity+=this.m_invI*((point.x-this.m_sweep.c.x)*impulse.y-(point.y-this.m_sweep.c.y)*impulse.x);}}ApplyLinearImpulseToCenter(impulse,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y;}}ApplyAngularImpulse(impulse,wake=true){if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_angularVelocity+=this.m_invI*impulse;}}GetMass(){return this.m_mass;}GetInertia(){return this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);}GetMassData(data){data.mass=this.m_mass;data.I=this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);data.center.Copy(this.m_sweep.localCenter);return data;}SetMassData(massData){if(this.m_world.IsLocked()){throw new Error();}if(this.m_type!==exports.b2BodyType.b2_dynamicBody){return;}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1;}this.m_invMass=1/this.m_mass;if(massData.I>0&&!this.m_fixedRotationFlag){this.m_I=massData.I-this.m_mass*b2Vec2.DotVV(massData.center,massData.center);this.m_invI=1/this.m_I;}const oldCenter=b2Body.SetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(massData.center);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity);}ResetMassData(){this.m_mass=0;this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_sweep.localCenter.SetZero();if(this.m_type===exports.b2BodyType.b2_staticBody||this.m_type===exports.b2BodyType.b2_kinematicBody){this.m_sweep.c0.Copy(this.m_xf.p);this.m_sweep.c.Copy(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a;return;}const localCenter=b2Body.ResetMassData_s_localCenter.SetZero();for(let f=this.m_fixtureList;f;f=f.m_next){if(f.m_density===0){continue;}const massData=f.GetMassData(b2Body.ResetMassData_s_massData);this.m_mass+=massData.mass;localCenter.x+=massData.center.x*massData.mass;localCenter.y+=massData.center.y*massData.mass;this.m_I+=massData.I;}if(this.m_mass>0){this.m_invMass=1/this.m_mass;localCenter.x*=this.m_invMass;localCenter.y*=this.m_invMass;}else {this.m_mass=1;this.m_invMass=1;}if(this.m_I>0&&!this.m_fixedRotationFlag){this.m_I-=this.m_mass*b2Vec2.DotVV(localCenter,localCenter);this.m_invI=1/this.m_I;}else {this.m_I=0;this.m_invI=0;}const oldCenter=b2Body.ResetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(localCenter);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity);}GetWorldPoint(localPoint,out){return b2Transform.MulXV(this.m_xf,localPoint,out);}GetWorldVector(localVector,out){return b2Rot.MulRV(this.m_xf.q,localVector,out);}GetLocalPoint(worldPoint,out){return b2Transform.MulTXV(this.m_xf,worldPoint,out);}GetLocalVector(worldVector,out){return b2Rot.MulTRV(this.m_xf.q,worldVector,out);}GetLinearVelocityFromWorldPoint(worldPoint,out){return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_sweep.c,b2Vec2.s_t0),out);}GetLinearVelocityFromLocalPoint(localPoint,out){return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint,out),out);}GetLinearDamping(){return this.m_linearDamping;}SetLinearDamping(linearDamping){this.m_linearDamping=linearDamping;}GetAngularDamping(){return this.m_angularDamping;}SetAngularDamping(angularDamping){this.m_angularDamping=angularDamping;}GetGravityScale(){return this.m_gravityScale;}SetGravityScale(scale){this.m_gravityScale=scale;}SetType(type){if(this.m_world.IsLocked()){throw new Error();}if(this.m_type===type){return;}this.m_type=type;this.ResetMassData();if(this.m_type===exports.b2BodyType.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_sweep.a0=this.m_sweep.a;this.m_sweep.c0.Copy(this.m_sweep.c);this.SynchronizeFixtures();}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;let ce=this.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;for(let f=this.m_fixtureList;f;f=f.m_next){f.TouchProxies();}}GetType(){return this.m_type;}SetBullet(flag){this.m_bulletFlag=flag;}IsBullet(){return this.m_bulletFlag;}SetSleepingAllowed(flag){this.m_autoSleepFlag=flag;if(!flag){this.SetAwake(true);}}IsSleepingAllowed(){return this.m_autoSleepFlag;}SetAwake(flag){if(flag){this.m_awakeFlag=true;this.m_sleepTime=0;}else {this.m_awakeFlag=false;this.m_sleepTime=0;this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0;}}IsAwake(){return this.m_awakeFlag;}SetActive(flag){if(this.m_world.IsLocked()){throw new Error();}if(flag===this.IsActive()){return;}this.m_activeFlag=flag;if(flag){for(let f=this.m_fixtureList;f;f=f.m_next){f.CreateProxies();}}else {for(let f=this.m_fixtureList;f;f=f.m_next){f.DestroyProxies();}let ce=this.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;}}IsActive(){return this.m_activeFlag;}SetFixedRotation(flag){if(this.m_fixedRotationFlag===flag){return;}this.m_fixedRotationFlag=flag;this.m_angularVelocity=0;this.ResetMassData();}IsFixedRotation(){return this.m_fixedRotationFlag;}GetFixtureList(){return this.m_fixtureList;}GetJointList(){return this.m_jointList;}GetContactList(){return this.m_contactList;}GetNext(){return this.m_next;}GetUserData(){return this.m_userData;}SetUserData(data){this.m_userData=data;}GetWorld(){return this.m_world;}Dump(log){const bodyIndex=this.m_islandIndex;log("{\n");log("  const bd: b2BodyDef = new b2BodyDef();\n");let type_str="";switch(this.m_type){case exports.b2BodyType.b2_staticBody:type_str="b2BodyType.b2_staticBody";break;case exports.b2BodyType.b2_kinematicBody:type_str="b2BodyType.b2_kinematicBody";break;case exports.b2BodyType.b2_dynamicBody:type_str="b2BodyType.b2_dynamicBody";break;}log("  bd.type = %s;\n",type_str);log("  bd.position.Set(%.15f, %.15f);\n",this.m_xf.p.x,this.m_xf.p.y);log("  bd.angle = %.15f;\n",this.m_sweep.a);log("  bd.linearVelocity.Set(%.15f, %.15f);\n",this.m_linearVelocity.x,this.m_linearVelocity.y);log("  bd.angularVelocity = %.15f;\n",this.m_angularVelocity);log("  bd.linearDamping = %.15f;\n",this.m_linearDamping);log("  bd.angularDamping = %.15f;\n",this.m_angularDamping);log("  bd.allowSleep = %s;\n",this.m_autoSleepFlag?"true":"false");log("  bd.awake = %s;\n",this.m_awakeFlag?"true":"false");log("  bd.fixedRotation = %s;\n",this.m_fixedRotationFlag?"true":"false");log("  bd.bullet = %s;\n",this.m_bulletFlag?"true":"false");log("  bd.active = %s;\n",this.m_activeFlag?"true":"false");log("  bd.gravityScale = %.15f;\n",this.m_gravityScale);log("\n");log("  bodies[%d] = this.m_world.CreateBody(bd);\n",this.m_islandIndex);log("\n");for(let f=this.m_fixtureList;f;f=f.m_next){log("  {\n");f.Dump(log,bodyIndex);log("  }\n");}log("}\n");}SynchronizeFixtures(){const xf1=b2Body.SynchronizeFixtures_s_xf1;xf1.q.SetAngle(this.m_sweep.a0);b2Rot.MulRV(xf1.q,this.m_sweep.localCenter,xf1.p);b2Vec2.SubVV(this.m_sweep.c0,xf1.p,xf1.p);const displacement=b2Vec2.SubVV(this.m_sweep.c,this.m_sweep.c0,b2Body.SynchronizeFixtures_s_displacement);for(let f=this.m_fixtureList;f;f=f.m_next){f.SynchronizeProxies(xf1,this.m_xf,displacement);}}SynchronizeTransform(){this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p);}ShouldCollide(other){if(this.m_type===exports.b2BodyType.b2_staticBody&&other.m_type===exports.b2BodyType.b2_staticBody){return false;}return this.ShouldCollideConnected(other);}ShouldCollideConnected(other){for(let jn=this.m_jointList;jn;jn=jn.next){if(jn.other===other){if(!jn.joint.m_collideConnected){return false;}}}return true;}Advance(alpha){this.m_sweep.Advance(alpha);this.m_sweep.c.Copy(this.m_sweep.c0);this.m_sweep.a=this.m_sweep.a0;this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p);}GetControllerList(){return this.m_controllerList;}GetControllerCount(){return this.m_controllerCount;}}b2Body.CreateFixtureShapeDensity_s_def=new b2FixtureDef();b2Body.SetMassData_s_oldCenter=new b2Vec2();b2Body.ResetMassData_s_localCenter=new b2Vec2();b2Body.ResetMassData_s_oldCenter=new b2Vec2();b2Body.ResetMassData_s_massData=new b2MassData();b2Body.SynchronizeFixtures_s_xf1=new b2Transform();b2Body.SynchronizeFixtures_s_displacement=new b2Vec2();(function(b2JointType){b2JointType[b2JointType["e_unknownJoint"]=0]="e_unknownJoint";b2JointType[b2JointType["e_revoluteJoint"]=1]="e_revoluteJoint";b2JointType[b2JointType["e_prismaticJoint"]=2]="e_prismaticJoint";b2JointType[b2JointType["e_distanceJoint"]=3]="e_distanceJoint";b2JointType[b2JointType["e_pulleyJoint"]=4]="e_pulleyJoint";b2JointType[b2JointType["e_mouseJoint"]=5]="e_mouseJoint";b2JointType[b2JointType["e_gearJoint"]=6]="e_gearJoint";b2JointType[b2JointType["e_wheelJoint"]=7]="e_wheelJoint";b2JointType[b2JointType["e_weldJoint"]=8]="e_weldJoint";b2JointType[b2JointType["e_frictionJoint"]=9]="e_frictionJoint";b2JointType[b2JointType["e_ropeJoint"]=10]="e_ropeJoint";b2JointType[b2JointType["e_motorJoint"]=11]="e_motorJoint";b2JointType[b2JointType["e_areaJoint"]=12]="e_areaJoint";})(exports.b2JointType||(exports.b2JointType={}));(function(b2LimitState){b2LimitState[b2LimitState["e_inactiveLimit"]=0]="e_inactiveLimit";b2LimitState[b2LimitState["e_atLowerLimit"]=1]="e_atLowerLimit";b2LimitState[b2LimitState["e_atUpperLimit"]=2]="e_atUpperLimit";b2LimitState[b2LimitState["e_equalLimits"]=3]="e_equalLimits";})(exports.b2LimitState||(exports.b2LimitState={}));class b2Jacobian{constructor(){this.linear=new b2Vec2();this.angularA=0;this.angularB=0;}SetZero(){this.linear.SetZero();this.angularA=0;this.angularB=0;return this;}Set(x,a1,a2){this.linear.Copy(x);this.angularA=a1;this.angularB=a2;return this;}}class b2JointEdge{constructor(joint){this._other=null;this.prev=null;this.next=null;this.joint=joint;}get other(){if(this._other===null){throw new Error();}return this._other;}set other(value){if(this._other!==null){throw new Error();}this._other=value;}Reset(){this._other=null;this.prev=null;this.next=null;}}class b2JointDef{constructor(type){this.type=exports.b2JointType.e_unknownJoint;this.userData=null;this.collideConnected=false;this.type=type;}}class b2Joint{constructor(def){this.m_type=exports.b2JointType.e_unknownJoint;this.m_prev=null;this.m_next=null;this.m_edgeA=new b2JointEdge(this);this.m_edgeB=new b2JointEdge(this);this.m_index=0;this.m_islandFlag=false;this.m_collideConnected=false;this.m_userData=null;this.m_type=def.type;this.m_edgeA.other=def.bodyB;this.m_edgeB.other=def.bodyA;this.m_bodyA=def.bodyA;this.m_bodyB=def.bodyB;this.m_collideConnected=b2Maybe(def.collideConnected,false);this.m_userData=b2Maybe(def.userData,null);}GetType(){return this.m_type;}GetBodyA(){return this.m_bodyA;}GetBodyB(){return this.m_bodyB;}GetNext(){return this.m_next;}GetUserData(){return this.m_userData;}SetUserData(data){this.m_userData=data;}IsActive(){return this.m_bodyA.IsActive()&&this.m_bodyB.IsActive();}GetCollideConnected(){return this.m_collideConnected;}Dump(log){log("// Dump is not supported for this joint type.\n");}ShiftOrigin(newOrigin){}}class b2DistanceJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_distanceJoint);this.localAnchorA=new b2Vec2();this.localAnchorB=new b2Vec2();this.length=1;this.frequencyHz=0;this.dampingRatio=0;}Initialize(b1,b2,anchor1,anchor2){this.bodyA=b1;this.bodyB=b2;this.bodyA.GetLocalPoint(anchor1,this.localAnchorA);this.bodyB.GetLocalPoint(anchor2,this.localAnchorB);this.length=b2Vec2.DistanceVV(anchor1,anchor2);this.frequencyHz=0;this.dampingRatio=0;}}class b2DistanceJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_bias=0;this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_gamma=0;this.m_impulse=0;this.m_length=0;this.m_indexA=0;this.m_indexB=0;this.m_u=new b2Vec2();this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_localAnchorA.Copy(def.localAnchorA);this.m_localAnchorB.Copy(def.localAnchorB);this.m_length=def.length;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse*this.m_u.x;out.y=inv_dt*this.m_impulse*this.m_u.y;return out;}GetReactionTorque(inv_dt){return 0;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}SetLength(length){this.m_length=length;}Length(){return this.m_length;}SetFrequency(hz){this.m_frequencyHz=hz;}GetFrequency(){return this.m_frequencyHz;}SetDampingRatio(ratio){this.m_dampingRatio=ratio;}GetDampingRatio(){return this.m_dampingRatio;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2DistanceJointDef = new b2DistanceJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.length = %.15f;\n",this.m_length);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.x=cB.x+this.m_rB.x-cA.x-this.m_rA.x;this.m_u.y=cB.y+this.m_rB.y-cA.y-this.m_rA.y;const length=this.m_u.Length();if(length>b2_linearSlop){this.m_u.SelfMul(1/length);}else {this.m_u.SetZero();}const crAu=b2Vec2.CrossVV(this.m_rA,this.m_u);const crBu=b2Vec2.CrossVV(this.m_rB,this.m_u);let invMass=this.m_invMassA+this.m_invIA*crAu*crAu+this.m_invMassB+this.m_invIB*crBu*crBu;this.m_mass=invMass!==0?1/invMass:0;if(this.m_frequencyHz>0){const C=length-this.m_length;const omega=2*b2_pi*this.m_frequencyHz;const d=2*this.m_mass*this.m_dampingRatio*omega;const k=this.m_mass*omega*omega;const h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invMass+=this.m_gamma;this.m_mass=invMass!==0?1/invMass:0;}else {this.m_gamma=0;this.m_bias=0;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2DistanceJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2DistanceJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2DistanceJoint.SolveVelocityConstraints_s_vpB);const Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));const impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_u,b2DistanceJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){if(this.m_frequencyHz>0){return true;}const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const u=this.m_u;u.x=cB.x+rB.x-cA.x-rA.x;u.y=cB.y+rB.y-cA.y-rA.y;const length=this.m_u.Normalize();let C=length-this.m_length;C=b2Clamp(C,-b2_maxLinearCorrection,b2_maxLinearCorrection);const impulse=-this.m_mass*C;const P=b2Vec2.MulSV(impulse,u,b2DistanceJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)<b2_linearSlop;}}b2DistanceJoint.InitVelocityConstraints_s_P=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2DistanceJoint.SolvePositionConstraints_s_P=new b2Vec2();class b2AreaJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_areaJoint);this.bodies=[];this.frequencyHz=0;this.dampingRatio=0;}AddBody(body){this.bodies.push(body);if(this.bodies.length===1){this.bodyA=body;}else if(this.bodies.length===2){this.bodyB=body;}}}class b2AreaJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_impulse=0;this.m_targetArea=0;this.m_delta=new b2Vec2();this.m_bodies=def.bodies;this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_targetLengths=b2MakeNumberArray(def.bodies.length);this.m_normals=b2Vec2.MakeArray(def.bodies.length);this.m_joints=[];this.m_deltas=b2Vec2.MakeArray(def.bodies.length);const djd=new b2DistanceJointDef();djd.frequencyHz=this.m_frequencyHz;djd.dampingRatio=this.m_dampingRatio;this.m_targetArea=0;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const next=this.m_bodies[(i+1)%this.m_bodies.length];const body_c=body.GetWorldCenter();const next_c=next.GetWorldCenter();this.m_targetLengths[i]=b2Vec2.DistanceVV(body_c,next_c);this.m_targetArea+=b2Vec2.CrossVV(body_c,next_c);djd.Initialize(body,next,body_c,next_c);this.m_joints[i]=body.GetWorld().CreateJoint(djd);}this.m_targetArea*=0.5;}GetAnchorA(out){return out;}GetAnchorB(out){return out;}GetReactionForce(inv_dt,out){return out;}GetReactionTorque(inv_dt){return 0;}SetFrequency(hz){this.m_frequencyHz=hz;for(let i=0;i<this.m_joints.length;++i){this.m_joints[i].SetFrequency(hz);}}GetFrequency(){return this.m_frequencyHz;}SetDampingRatio(ratio){this.m_dampingRatio=ratio;for(let i=0;i<this.m_joints.length;++i){this.m_joints[i].SetDampingRatio(ratio);}}GetDampingRatio(){return this.m_dampingRatio;}Dump(log){log("Area joint dumping is not supported.\n");}InitVelocityConstraints(data){for(let i=0;i<this.m_bodies.length;++i){const prev=this.m_bodies[(i+this.m_bodies.length-1)%this.m_bodies.length];const next=this.m_bodies[(i+1)%this.m_bodies.length];const prev_c=data.positions[prev.m_islandIndex].c;const next_c=data.positions[next.m_islandIndex].c;const delta=this.m_deltas[i];b2Vec2.SubVV(next_c,prev_c,delta);}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const body_v=data.velocities[body.m_islandIndex].v;const delta=this.m_deltas[i];body_v.x+=body.m_invMass*delta.y*0.5*this.m_impulse;body_v.y+=body.m_invMass*-delta.x*0.5*this.m_impulse;}}else {this.m_impulse=0;}}SolveVelocityConstraints(data){let dotMassSum=0;let crossMassSum=0;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const body_v=data.velocities[body.m_islandIndex].v;const delta=this.m_deltas[i];dotMassSum+=delta.LengthSquared()/body.GetMass();crossMassSum+=b2Vec2.CrossVV(body_v,delta);}const lambda=-2*crossMassSum/dotMassSum;this.m_impulse+=lambda;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const body_v=data.velocities[body.m_islandIndex].v;const delta=this.m_deltas[i];body_v.x+=body.m_invMass*delta.y*0.5*lambda;body_v.y+=body.m_invMass*-delta.x*0.5*lambda;}}SolvePositionConstraints(data){let perimeter=0;let area=0;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const next=this.m_bodies[(i+1)%this.m_bodies.length];const body_c=data.positions[body.m_islandIndex].c;const next_c=data.positions[next.m_islandIndex].c;const delta=b2Vec2.SubVV(next_c,body_c,this.m_delta);let dist=delta.Length();if(dist<b2_epsilon){dist=1;}this.m_normals[i].x=delta.y/dist;this.m_normals[i].y=-delta.x/dist;perimeter+=dist;area+=b2Vec2.CrossVV(body_c,next_c);}area*=0.5;const deltaArea=this.m_targetArea-area;const toExtrude=0.5*deltaArea/perimeter;let done=true;for(let i=0;i<this.m_bodies.length;++i){const body=this.m_bodies[i];const body_c=data.positions[body.m_islandIndex].c;const next_i=(i+1)%this.m_bodies.length;const delta=b2Vec2.AddVV(this.m_normals[i],this.m_normals[next_i],this.m_delta);delta.SelfMul(toExtrude);const norm_sq=delta.LengthSquared();if(norm_sq>b2Sq(b2_maxLinearCorrection)){delta.SelfMul(b2_maxLinearCorrection/b2Sqrt(norm_sq));}if(norm_sq>b2Sq(b2_linearSlop)){done=false;}body_c.x+=delta.x;body_c.y+=delta.y;}return done;}}class b2FrictionJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_frictionJoint);this.localAnchorA=new b2Vec2();this.localAnchorB=new b2Vec2();this.maxForce=0;this.maxTorque=0;}Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);}}class b2FrictionJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_linearImpulse=new b2Vec2();this.m_angularImpulse=0;this.m_maxForce=0;this.m_maxTorque=0;this.m_indexA=0;this.m_indexB=0;this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_linearMass=new b2Mat22();this.m_angularMass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_K=new b2Mat22();this.m_localAnchorA.Copy(def.localAnchorA);this.m_localAnchorB.Copy(def.localAnchorB);this.m_linearImpulse.SetZero();this.m_maxForce=b2Maybe(def.maxForce,0);this.m_maxTorque=b2Maybe(def.maxTorque,0);this.m_linearMass.SetZero();}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass;}if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;const P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_angularImpulse);}else {this.m_linearImpulse.SetZero();this.m_angularImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const h=data.step.dt;{const Cdot=wB-wA;let impulse=-this.m_angularMass*Cdot;const oldImpulse=this.m_angularImpulse;const maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}{const Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2);const impulseV=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg();const oldImpulseV=b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulseV);const maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(maxImpulse);}b2Vec2.SubVV(this.m_linearImpulse,oldImpulseV,impulseV);vA.SelfMulSub(mA,impulseV);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulseV);vB.SelfMulAdd(mB,impulseV);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulseV);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){return true;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_linearImpulse.x;out.y=inv_dt*this.m_linearImpulse.y;return out;}GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}SetMaxForce(force){this.m_maxForce=force;}GetMaxForce(){return this.m_maxForce;}SetMaxTorque(torque){this.m_maxTorque=torque;}GetMaxTorque(){return this.m_maxTorque;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2FrictionJointDef = new b2FrictionJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.maxForce = %.15f;\n",this.m_maxForce);log("  jd.maxTorque = %.15f;\n",this.m_maxTorque);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_impulseV=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV=new b2Vec2();class b2GearJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_gearJoint);this.ratio=1;}}class b2GearJoint extends b2Joint{constructor(def){super(def);this.m_typeA=exports.b2JointType.e_unknownJoint;this.m_typeB=exports.b2JointType.e_unknownJoint;this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_localAnchorC=new b2Vec2();this.m_localAnchorD=new b2Vec2();this.m_localAxisC=new b2Vec2();this.m_localAxisD=new b2Vec2();this.m_referenceAngleA=0;this.m_referenceAngleB=0;this.m_constant=0;this.m_ratio=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_indexC=0;this.m_indexD=0;this.m_lcA=new b2Vec2();this.m_lcB=new b2Vec2();this.m_lcC=new b2Vec2();this.m_lcD=new b2Vec2();this.m_mA=0;this.m_mB=0;this.m_mC=0;this.m_mD=0;this.m_iA=0;this.m_iB=0;this.m_iC=0;this.m_iD=0;this.m_JvAC=new b2Vec2();this.m_JvBD=new b2Vec2();this.m_JwA=0;this.m_JwB=0;this.m_JwC=0;this.m_JwD=0;this.m_mass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_qC=new b2Rot();this.m_qD=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_lalcC=new b2Vec2();this.m_lalcD=new b2Vec2();this.m_joint1=def.joint1;this.m_joint2=def.joint2;this.m_typeA=this.m_joint1.GetType();this.m_typeB=this.m_joint2.GetType();let coordinateA,coordinateB;this.m_bodyC=this.m_joint1.GetBodyA();this.m_bodyA=this.m_joint1.GetBodyB();const xfA=this.m_bodyA.m_xf;const aA=this.m_bodyA.m_sweep.a;const xfC=this.m_bodyC.m_xf;const aC=this.m_bodyC.m_sweep.a;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){const revolute=def.joint1;this.m_localAnchorC.Copy(revolute.m_localAnchorA);this.m_localAnchorA.Copy(revolute.m_localAnchorB);this.m_referenceAngleA=revolute.m_referenceAngle;this.m_localAxisC.SetZero();coordinateA=aA-aC-this.m_referenceAngleA;}else {const prismatic=def.joint1;this.m_localAnchorC.Copy(prismatic.m_localAnchorA);this.m_localAnchorA.Copy(prismatic.m_localAnchorB);this.m_referenceAngleA=prismatic.m_referenceAngle;this.m_localAxisC.Copy(prismatic.m_localXAxisA);const pC=this.m_localAnchorC;const pA=b2Rot.MulTRV(xfC.q,b2Vec2.AddVV(b2Rot.MulRV(xfA.q,this.m_localAnchorA,b2Vec2.s_t0),b2Vec2.SubVV(xfA.p,xfC.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),this.m_localAxisC);}this.m_bodyD=this.m_joint2.GetBodyA();this.m_bodyB=this.m_joint2.GetBodyB();const xfB=this.m_bodyB.m_xf;const aB=this.m_bodyB.m_sweep.a;const xfD=this.m_bodyD.m_xf;const aD=this.m_bodyD.m_sweep.a;if(this.m_typeB===exports.b2JointType.e_revoluteJoint){const revolute=def.joint2;this.m_localAnchorD.Copy(revolute.m_localAnchorA);this.m_localAnchorB.Copy(revolute.m_localAnchorB);this.m_referenceAngleB=revolute.m_referenceAngle;this.m_localAxisD.SetZero();coordinateB=aB-aD-this.m_referenceAngleB;}else {const prismatic=def.joint2;this.m_localAnchorD.Copy(prismatic.m_localAnchorA);this.m_localAnchorB.Copy(prismatic.m_localAnchorB);this.m_referenceAngleB=prismatic.m_referenceAngle;this.m_localAxisD.Copy(prismatic.m_localXAxisA);const pD=this.m_localAnchorD;const pB=b2Rot.MulTRV(xfD.q,b2Vec2.AddVV(b2Rot.MulRV(xfB.q,this.m_localAnchorB,b2Vec2.s_t0),b2Vec2.SubVV(xfB.p,xfD.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),this.m_localAxisD);}this.m_ratio=b2Maybe(def.ratio,1);this.m_constant=coordinateA+this.m_ratio*coordinateB;this.m_impulse=0;}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_indexC=this.m_bodyC.m_islandIndex;this.m_indexD=this.m_bodyD.m_islandIndex;this.m_lcA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_lcB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_lcC.Copy(this.m_bodyC.m_sweep.localCenter);this.m_lcD.Copy(this.m_bodyD.m_sweep.localCenter);this.m_mA=this.m_bodyA.m_invMass;this.m_mB=this.m_bodyB.m_invMass;this.m_mC=this.m_bodyC.m_invMass;this.m_mD=this.m_bodyD.m_invMass;this.m_iA=this.m_bodyA.m_invI;this.m_iB=this.m_bodyB.m_invI;this.m_iC=this.m_bodyC.m_invI;this.m_iD=this.m_bodyD.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const aC=data.positions[this.m_indexC].a;const vC=data.velocities[this.m_indexC].v;let wC=data.velocities[this.m_indexC].w;const aD=data.positions[this.m_indexD].a;const vD=data.velocities[this.m_indexD].v;let wD=data.velocities[this.m_indexD].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB),qC=this.m_qC.SetAngle(aC),qD=this.m_qD.SetAngle(aD);this.m_mass=0;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){this.m_JvAC.SetZero();this.m_JwA=1;this.m_JwC=1;this.m_mass+=this.m_iA+this.m_iC;}else {const u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorC,this.m_lcC,this.m_lalcC);const rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.InitVelocityConstraints_s_rC);b2Vec2.SubVV(this.m_localAnchorA,this.m_lcA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.InitVelocityConstraints_s_rA);this.m_JvAC.Copy(u);this.m_JwC=b2Vec2.CrossVV(rC,u);this.m_JwA=b2Vec2.CrossVV(rA,u);this.m_mass+=this.m_mC+this.m_mA+this.m_iC*this.m_JwC*this.m_JwC+this.m_iA*this.m_JwA*this.m_JwA;}if(this.m_typeB===exports.b2JointType.e_revoluteJoint){this.m_JvBD.SetZero();this.m_JwB=this.m_ratio;this.m_JwD=this.m_ratio;this.m_mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);}else {const u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorD,this.m_lcD,this.m_lalcD);const rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.InitVelocityConstraints_s_rD);b2Vec2.SubVV(this.m_localAnchorB,this.m_lcB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.InitVelocityConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,u,this.m_JvBD);this.m_JwD=this.m_ratio*b2Vec2.CrossVV(rD,u);this.m_JwB=this.m_ratio*b2Vec2.CrossVV(rB,u);this.m_mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*this.m_JwD*this.m_JwD+this.m_iB*this.m_JwB*this.m_JwB;}this.m_mass=this.m_mass>0?1/this.m_mass:0;if(data.step.warmStarting){vA.SelfMulAdd(this.m_mA*this.m_impulse,this.m_JvAC);wA+=this.m_iA*this.m_impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*this.m_impulse,this.m_JvBD);wB+=this.m_iB*this.m_impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*this.m_impulse,this.m_JvAC);wC-=this.m_iC*this.m_impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*this.m_impulse,this.m_JvBD);wD-=this.m_iD*this.m_impulse*this.m_JwD;}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vC=data.velocities[this.m_indexC].v;let wC=data.velocities[this.m_indexC].w;const vD=data.velocities[this.m_indexD].v;let wD=data.velocities[this.m_indexD].w;let Cdot=b2Vec2.DotVV(this.m_JvAC,b2Vec2.SubVV(vA,vC,b2Vec2.s_t0))+b2Vec2.DotVV(this.m_JvBD,b2Vec2.SubVV(vB,vD,b2Vec2.s_t0));Cdot+=this.m_JwA*wA-this.m_JwC*wC+(this.m_JwB*wB-this.m_JwD*wD);const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;vA.SelfMulAdd(this.m_mA*impulse,this.m_JvAC);wA+=this.m_iA*impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*impulse,this.m_JvBD);wB+=this.m_iB*impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*impulse,this.m_JvAC);wC-=this.m_iC*impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*impulse,this.m_JvBD);wD-=this.m_iD*impulse*this.m_JwD;data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const cC=data.positions[this.m_indexC].c;let aC=data.positions[this.m_indexC].a;const cD=data.positions[this.m_indexD].c;let aD=data.positions[this.m_indexD].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB),qC=this.m_qC.SetAngle(aC),qD=this.m_qD.SetAngle(aD);const linearError=0;let coordinateA,coordinateB;const JvAC=this.m_JvAC,JvBD=this.m_JvBD;let JwA,JwB,JwC,JwD;let mass=0;if(this.m_typeA===exports.b2JointType.e_revoluteJoint){JvAC.SetZero();JwA=1;JwC=1;mass+=this.m_iA+this.m_iC;coordinateA=aA-aC-this.m_referenceAngleA;}else {const u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.SolvePositionConstraints_s_u);const rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.SolvePositionConstraints_s_rC);const rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.SolvePositionConstraints_s_rA);JvAC.Copy(u);JwC=b2Vec2.CrossVV(rC,u);JwA=b2Vec2.CrossVV(rA,u);mass+=this.m_mC+this.m_mA+this.m_iC*JwC*JwC+this.m_iA*JwA*JwA;const pC=this.m_lalcC;const pA=b2Rot.MulTRV(qC,b2Vec2.AddVV(rA,b2Vec2.SubVV(cA,cC,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),this.m_localAxisC);}if(this.m_typeB===exports.b2JointType.e_revoluteJoint){JvBD.SetZero();JwB=this.m_ratio;JwD=this.m_ratio;mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);coordinateB=aB-aD-this.m_referenceAngleB;}else {const u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.SolvePositionConstraints_s_u);const rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.SolvePositionConstraints_s_rD);const rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.SolvePositionConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,u,JvBD);JwD=this.m_ratio*b2Vec2.CrossVV(rD,u);JwB=this.m_ratio*b2Vec2.CrossVV(rB,u);mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*JwD*JwD+this.m_iB*JwB*JwB;const pD=this.m_lalcD;const pB=b2Rot.MulTRV(qD,b2Vec2.AddVV(rB,b2Vec2.SubVV(cB,cD,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),this.m_localAxisD);}const C=coordinateA+this.m_ratio*coordinateB-this.m_constant;let impulse=0;if(mass>0){impulse=-C/mass;}cA.SelfMulAdd(this.m_mA*impulse,JvAC);aA+=this.m_iA*impulse*JwA;cB.SelfMulAdd(this.m_mB*impulse,JvBD);aB+=this.m_iB*impulse*JwB;cC.SelfMulSub(this.m_mC*impulse,JvAC);aC-=this.m_iC*impulse*JwC;cD.SelfMulSub(this.m_mD*impulse,JvBD);aD-=this.m_iD*impulse*JwD;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;data.positions[this.m_indexC].a=aC;data.positions[this.m_indexD].a=aD;return linearError<b2_linearSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_JvAC,out);}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse*this.m_JwA;}GetJoint1(){return this.m_joint1;}GetJoint2(){return this.m_joint2;}GetRatio(){return this.m_ratio;}SetRatio(ratio){this.m_ratio=ratio;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;const index1=this.m_joint1.m_index;const index2=this.m_joint2.m_index;log("  const jd: b2GearJointDef = new b2GearJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.joint1 = joints[%d];\n",index1);log("  jd.joint2 = joints[%d];\n",index2);log("  jd.ratio = %.15f;\n",this.m_ratio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2GearJoint.InitVelocityConstraints_s_u=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rA=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rB=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rC=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rD=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_u=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rA=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rB=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rC=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rD=new b2Vec2();class b2MotorJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_motorJoint);this.linearOffset=new b2Vec2(0,0);this.angularOffset=0;this.maxForce=1;this.maxTorque=1;this.correctionFactor=0.3;}Initialize(bA,bB){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(this.bodyB.GetPosition(),this.linearOffset);const angleA=this.bodyA.GetAngle();const angleB=this.bodyB.GetAngle();this.angularOffset=angleB-angleA;}}class b2MotorJoint extends b2Joint{constructor(def){super(def);this.m_linearOffset=new b2Vec2();this.m_angularOffset=0;this.m_linearImpulse=new b2Vec2();this.m_angularImpulse=0;this.m_maxForce=0;this.m_maxTorque=0;this.m_correctionFactor=0.3;this.m_indexA=0;this.m_indexB=0;this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_linearError=new b2Vec2();this.m_angularError=0;this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_linearMass=new b2Mat22();this.m_angularMass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_K=new b2Mat22();this.m_linearOffset.Copy(b2Maybe(def.linearOffset,b2Vec2.ZERO));this.m_linearImpulse.SetZero();this.m_maxForce=b2Maybe(def.maxForce,0);this.m_maxTorque=b2Maybe(def.maxTorque,0);this.m_correctionFactor=b2Maybe(def.correctionFactor,0.3);}GetAnchorA(out){const pos=this.m_bodyA.GetPosition();out.x=pos.x;out.y=pos.y;return out;}GetAnchorB(out){const pos=this.m_bodyB.GetPosition();out.x=pos.x;out.y=pos.y;return out;}GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_linearImpulse,out);}GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;}SetLinearOffset(linearOffset){if(!b2Vec2.IsEqualToV(linearOffset,this.m_linearOffset)){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_linearOffset.Copy(linearOffset);}}GetLinearOffset(){return this.m_linearOffset;}SetAngularOffset(angularOffset){if(angularOffset!==this.m_angularOffset){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_angularOffset=angularOffset;}}GetAngularOffset(){return this.m_angularOffset;}SetMaxForce(force){this.m_maxForce=force;}GetMaxForce(){return this.m_maxForce;}SetMaxTorque(torque){this.m_maxTorque=torque;}GetMaxTorque(){return this.m_maxTorque;}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);const rA=b2Rot.MulRV(qA,b2Vec2.SubVV(this.m_linearOffset,this.m_localCenterA,b2Vec2.s_t0),this.m_rA);const rB=b2Rot.MulRV(qB,b2Vec2.NegV(this.m_localCenterB,b2Vec2.s_t0),this.m_rB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass;}b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),this.m_linearError);this.m_angularError=aB-aA-this.m_angularOffset;if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;const P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(rB,P)+this.m_angularImpulse);}else {this.m_linearImpulse.SetZero();this.m_angularImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const h=data.step.dt;const inv_h=data.step.inv_dt;{const Cdot=wB-wA+inv_h*this.m_correctionFactor*this.m_angularError;let impulse=-this.m_angularMass*Cdot;const oldImpulse=this.m_angularImpulse;const maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}{const rA=this.m_rA;const rB=this.m_rB;const Cdot_v2=b2Vec2.AddVV(b2Vec2.SubVV(b2Vec2.AddVV(vB,b2Vec2.CrossSV(wB,rB,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.AddVV(vA,b2Vec2.CrossSV(wA,rA,b2Vec2.s_t1),b2Vec2.s_t1),b2Vec2.s_t2),b2Vec2.MulSV(inv_h*this.m_correctionFactor,this.m_linearError,b2Vec2.s_t3),b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2);const impulse_v2=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg();const oldImpulse_v2=b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulse_v2);const maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>maxImpulse*maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(maxImpulse);}b2Vec2.SubVV(this.m_linearImpulse,oldImpulse_v2,impulse_v2);vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(rB,impulse_v2);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){return true;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2MotorJointDef = new b2MotorJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.linearOffset.Set(%.15f, %.15f);\n",this.m_linearOffset.x,this.m_linearOffset.y);log("  jd.angularOffset = %.15f;\n",this.m_angularOffset);log("  jd.maxForce = %.15f;\n",this.m_maxForce);log("  jd.maxTorque = %.15f;\n",this.m_maxTorque);log("  jd.correctionFactor = %.15f;\n",this.m_correctionFactor);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2=new b2Vec2();class b2MouseJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_mouseJoint);this.target=new b2Vec2();this.maxForce=0;this.frequencyHz=5;this.dampingRatio=0.7;}}class b2MouseJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorB=new b2Vec2();this.m_targetA=new b2Vec2();this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_beta=0;this.m_impulse=new b2Vec2();this.m_maxForce=0;this.m_gamma=0;this.m_indexA=0;this.m_indexB=0;this.m_rB=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassB=0;this.m_invIB=0;this.m_mass=new b2Mat22();this.m_C=new b2Vec2();this.m_qB=new b2Rot();this.m_lalcB=new b2Vec2();this.m_K=new b2Mat22();this.m_targetA.Copy(b2Maybe(def.target,b2Vec2.ZERO));b2Transform.MulTXV(this.m_bodyB.GetTransform(),this.m_targetA,this.m_localAnchorB);this.m_maxForce=b2Maybe(def.maxForce,0);this.m_impulse.SetZero();this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_beta=0;this.m_gamma=0;}SetTarget(target){if(!this.m_bodyB.IsAwake()){this.m_bodyB.SetAwake(true);}this.m_targetA.Copy(target);}GetTarget(){return this.m_targetA;}SetMaxForce(maxForce){this.m_maxForce=maxForce;}GetMaxForce(){return this.m_maxForce;}SetFrequency(hz){this.m_frequencyHz=hz;}GetFrequency(){return this.m_frequencyHz;}SetDampingRatio(ratio){this.m_dampingRatio=ratio;}GetDampingRatio(){return this.m_dampingRatio;}InitVelocityConstraints(data){this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIB=this.m_bodyB.m_invI;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qB=this.m_qB.SetAngle(aB);const mass=this.m_bodyB.GetMass();const omega=2*b2_pi*this.m_frequencyHz;const d=2*mass*this.m_dampingRatio*omega;const k=mass*(omega*omega);const h=data.step.dt;this.m_gamma=h*(d+h*k);if(this.m_gamma!==0){this.m_gamma=1/this.m_gamma;}this.m_beta=h*k*this.m_gamma;b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const K=this.m_K;K.ex.x=this.m_invMassB+this.m_invIB*this.m_rB.y*this.m_rB.y+this.m_gamma;K.ex.y=-this.m_invIB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=this.m_invMassB+this.m_invIB*this.m_rB.x*this.m_rB.x+this.m_gamma;K.GetInverse(this.m_mass);this.m_C.x=cB.x+this.m_rB.x-this.m_targetA.x;this.m_C.y=cB.y+this.m_rB.y-this.m_targetA.y;this.m_C.SelfMul(this.m_beta);wB*=0.98;if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);vB.x+=this.m_invMassB*this.m_impulse.x;vB.y+=this.m_invMassB*this.m_impulse.y;wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,this.m_impulse);}else {this.m_impulse.SetZero();}data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const Cdot=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2MouseJoint.SolveVelocityConstraints_s_Cdot);const impulse=b2Mat22.MulMV(this.m_mass,b2Vec2.AddVV(Cdot,b2Vec2.AddVV(this.m_C,b2Vec2.MulSV(this.m_gamma,this.m_impulse,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0).SelfNeg(),b2MouseJoint.SolveVelocityConstraints_s_impulse);const oldImpulse=b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse);this.m_impulse.SelfAdd(impulse);const maxImpulse=data.step.dt*this.m_maxForce;if(this.m_impulse.LengthSquared()>maxImpulse*maxImpulse){this.m_impulse.SelfMul(maxImpulse/this.m_impulse.Length());}b2Vec2.SubVV(this.m_impulse,oldImpulse,impulse);vB.SelfMulAdd(this.m_invMassB,impulse);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,impulse);data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){return true;}GetAnchorA(out){out.x=this.m_targetA.x;out.y=this.m_targetA.y;return out;}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_impulse,out);}GetReactionTorque(inv_dt){return 0;}Dump(log){log("Mouse joint dumping is not supported.\n");}ShiftOrigin(newOrigin){this.m_targetA.SelfSub(newOrigin);}}b2MouseJoint.SolveVelocityConstraints_s_Cdot=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_impulse=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_oldImpulse=new b2Vec2();class b2PrismaticJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_prismaticJoint);this.localAnchorA=new b2Vec2();this.localAnchorB=new b2Vec2();this.localAxisA=new b2Vec2(1,0);this.referenceAngle=0;this.enableLimit=false;this.lowerTranslation=0;this.upperTranslation=0;this.enableMotor=false;this.maxMotorForce=0;this.motorSpeed=0;}Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();}}class b2PrismaticJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_localXAxisA=new b2Vec2();this.m_localYAxisA=new b2Vec2();this.m_referenceAngle=0;this.m_impulse=new b2Vec3(0,0,0);this.m_motorImpulse=0;this.m_lowerTranslation=0;this.m_upperTranslation=0;this.m_maxMotorForce=0;this.m_motorSpeed=0;this.m_enableLimit=false;this.m_enableMotor=false;this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_indexA=0;this.m_indexB=0;this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_axis=new b2Vec2(0,0);this.m_perp=new b2Vec2(0,0);this.m_s1=0;this.m_s2=0;this.m_a1=0;this.m_a2=0;this.m_K=new b2Mat33();this.m_K3=new b2Mat33();this.m_K2=new b2Mat22();this.m_motorMass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_localXAxisA.Copy(b2Maybe(def.localAxisA,new b2Vec2(1,0))).SelfNormalize();b2Vec2.CrossOneV(this.m_localXAxisA,this.m_localYAxisA);this.m_referenceAngle=b2Maybe(def.referenceAngle,0);this.m_lowerTranslation=b2Maybe(def.lowerTranslation,0);this.m_upperTranslation=b2Maybe(def.upperTranslation,0);this.m_maxMotorForce=b2Maybe(def.maxMotorForce,0);this.m_motorSpeed=b2Maybe(def.motorSpeed,0);this.m_enableLimit=b2Maybe(def.enableLimit,false);this.m_enableMotor=b2Maybe(def.enableMotor,false);}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_d);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;{b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);this.m_a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_axis);this.m_a2=b2Vec2.CrossVV(rB,this.m_axis);this.m_motorMass=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}}{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);this.m_s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_perp);this.m_s2=b2Vec2.CrossVV(rB,this.m_perp);this.m_K.ex.x=mA+mB+iA*this.m_s1*this.m_s1+iB*this.m_s2*this.m_s2;this.m_K.ex.y=iA*this.m_s1+iB*this.m_s2;this.m_K.ex.z=iA*this.m_s1*this.m_a1+iB*this.m_s2*this.m_a2;this.m_K.ey.x=this.m_K.ex.y;this.m_K.ey.y=iA+iB;if(this.m_K.ey.y===0){this.m_K.ey.y=1;}this.m_K.ey.z=iA*this.m_a1+iB*this.m_a2;this.m_K.ez.x=this.m_K.ex.z;this.m_K.ez.y=this.m_K.ey.z;this.m_K.ez.z=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;}if(this.m_enableLimit){const jointTranslation=b2Vec2.DotVV(this.m_axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){this.m_limitState=exports.b2LimitState.e_equalLimits;}else if(jointTranslation<=this.m_lowerTranslation){if(this.m_limitState!==exports.b2LimitState.e_atLowerLimit){this.m_limitState=exports.b2LimitState.e_atLowerLimit;this.m_impulse.z=0;}}else if(jointTranslation>=this.m_upperTranslation){if(this.m_limitState!==exports.b2LimitState.e_atUpperLimit){this.m_limitState=exports.b2LimitState.e_atUpperLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}if(!this.m_enableMotor){this.m_motorImpulse=0;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;const P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(this.m_motorImpulse+this.m_impulse.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_P);const LA=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;const LB=this.m_impulse.x*this.m_s2+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}else {this.m_impulse.SetZero();this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits){const Cdot=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;let impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorForce;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;const P=b2Vec2.MulSV(impulse,this.m_axis,b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_a1;const LB=impulse*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}const Cdot1_x=b2Vec2.DotVV(this.m_perp,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_s2*wB-this.m_s1*wA;const Cdot1_y=wB-wA;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit){const Cdot2=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;const f1=b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse);const df3=this.m_K.Solve33(-Cdot1_x,-Cdot1_y,-Cdot2,b2PrismaticJoint.SolveVelocityConstraints_s_df3);this.m_impulse.SelfAdd(df3);if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){this.m_impulse.z=b2Max(this.m_impulse.z,0);}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){this.m_impulse.z=b2Min(this.m_impulse.z,0);}const b_x=-Cdot1_x-(this.m_impulse.z-f1.z)*this.m_K.ez.x;const b_y=-Cdot1_y-(this.m_impulse.z-f1.z)*this.m_K.ez.y;const f2r=this.m_K.Solve22(b_x,b_y,b2PrismaticJoint.SolveVelocityConstraints_s_f2r);f2r.x+=f1.x;f2r.y+=f1.y;this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;df3.x=this.m_impulse.x-f1.x;df3.y=this.m_impulse.y-f1.y;df3.z=this.m_impulse.z-f1.z;const P=b2Vec2.AddVV(b2Vec2.MulSV(df3.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(df3.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=df3.x*this.m_s1+df3.y+df3.z*this.m_a1;const LB=df3.x*this.m_s2+df3.y+df3.z*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}else {const df2=this.m_K.Solve22(-Cdot1_x,-Cdot1_y,b2PrismaticJoint.SolveVelocityConstraints_s_df2);this.m_impulse.x+=df2.x;this.m_impulse.y+=df2.y;const P=b2Vec2.MulSV(df2.x,this.m_perp,b2PrismaticJoint.SolveVelocityConstraints_s_P);const LA=df2.x*this.m_s1+df2.y;const LB=df2.x*this.m_s2+df2.y;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_d);const axis=b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);const a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),axis);const a2=b2Vec2.CrossVV(rB,axis);const perp=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);const s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),perp);const s2=b2Vec2.CrossVV(rB,perp);let impulse=b2PrismaticJoint.SolvePositionConstraints_s_impulse;const C1_x=b2Vec2.DotVV(perp,d);const C1_y=aB-aA-this.m_referenceAngle;let linearError=b2Abs(C1_x);const angularError=b2Abs(C1_y);let active=false;let C2=0;if(this.m_enableLimit){const translation=b2Vec2.DotVV(axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){C2=b2Clamp(translation,-b2_maxLinearCorrection,b2_maxLinearCorrection);linearError=b2Max(linearError,b2Abs(translation));active=true;}else if(translation<=this.m_lowerTranslation){C2=b2Clamp(translation-this.m_lowerTranslation+b2_linearSlop,-b2_maxLinearCorrection,0);linearError=b2Max(linearError,this.m_lowerTranslation-translation);active=true;}else if(translation>=this.m_upperTranslation){C2=b2Clamp(translation-this.m_upperTranslation-b2_linearSlop,0,b2_maxLinearCorrection);linearError=b2Max(linearError,translation-this.m_upperTranslation);active=true;}}if(active){const k11=mA+mB+iA*s1*s1+iB*s2*s2;const k12=iA*s1+iB*s2;const k13=iA*s1*a1+iB*s2*a2;let k22=iA+iB;if(k22===0){k22=1;}const k23=iA*a1+iB*a2;const k33=mA+mB+iA*a1*a1+iB*a2*a2;const K=this.m_K3;K.ex.SetXYZ(k11,k12,k13);K.ey.SetXYZ(k12,k22,k23);K.ez.SetXYZ(k13,k23,k33);impulse=K.Solve33(-C1_x,-C1_y,-C2,impulse);}else {const k11=mA+mB+iA*s1*s1+iB*s2*s2;const k12=iA*s1+iB*s2;let k22=iA+iB;if(k22===0){k22=1;}const K2=this.m_K2;K2.ex.Set(k11,k12);K2.ey.Set(k12,k22);const impulse1=K2.Solve(-C1_x,-C1_y,b2PrismaticJoint.SolvePositionConstraints_s_impulse1);impulse.x=impulse1.x;impulse.y=impulse1.y;impulse.z=0;}const P=b2Vec2.AddVV(b2Vec2.MulSV(impulse.x,perp,b2Vec2.s_t0),b2Vec2.MulSV(impulse.z,axis,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_P);const LA=impulse.x*s1+impulse.y+impulse.z*a1;const LB=impulse.x*s2+impulse.y+impulse.z*a2;cA.SelfMulSub(mA,P);aA-=iA*LA;cB.SelfMulAdd(mB,P);aB+=iB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError<=b2_linearSlop&&angularError<=b2_angularSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.x);out.y=inv_dt*(this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.y);return out;}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.y;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}GetLocalAxisA(){return this.m_localXAxisA;}GetReferenceAngle(){return this.m_referenceAngle;}GetJointTranslation(){const pA=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PrismaticJoint.GetJointTranslation_s_pA);const pB=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PrismaticJoint.GetJointTranslation_s_pB);const d=b2Vec2.SubVV(pB,pA,b2PrismaticJoint.GetJointTranslation_s_d);const axis=this.m_bodyA.GetWorldVector(this.m_localXAxisA,b2PrismaticJoint.GetJointTranslation_s_axis);const translation=b2Vec2.DotVV(d,axis);return translation;}GetJointSpeed(){const bA=this.m_bodyA;const bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);const rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);const rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);const pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);const pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);const d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);const axis=bA.GetWorldVector(this.m_localXAxisA,this.m_axis);const vA=bA.m_linearVelocity;const vB=bB.m_linearVelocity;const wA=bA.m_angularVelocity;const wB=bB.m_angularVelocity;const speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed;}IsLimitEnabled(){return this.m_enableLimit;}EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0;}}GetLowerLimit(){return this.m_lowerTranslation;}GetUpperLimit(){return this.m_upperTranslation;}SetLimits(lower,upper){if(lower!==this.m_lowerTranslation||upper!==this.m_upperTranslation){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper;this.m_impulse.z=0;}}IsMotorEnabled(){return this.m_enableMotor;}EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}}SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}}GetMotorSpeed(){return this.m_motorSpeed;}SetMaxMotorForce(force){if(force!==this.m_maxMotorForce){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force;}}GetMaxMotorForce(){return this.m_maxMotorForce;}GetMotorForce(inv_dt){return inv_dt*this.m_motorImpulse;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2PrismaticJointDef = new b2PrismaticJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log("  jd.lowerTranslation = %.15f;\n",this.m_lowerTranslation);log("  jd.upperTranslation = %.15f;\n",this.m_upperTranslation);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorForce = %.15f;\n",this.m_maxMotorForce);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2PrismaticJoint.InitVelocityConstraints_s_d=new b2Vec2();b2PrismaticJoint.InitVelocityConstraints_s_P=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_f2r=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_f1=new b2Vec3();b2PrismaticJoint.SolveVelocityConstraints_s_df3=new b2Vec3();b2PrismaticJoint.SolveVelocityConstraints_s_df2=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_d=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_impulse=new b2Vec3();b2PrismaticJoint.SolvePositionConstraints_s_impulse1=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_P=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_pA=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_pB=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_d=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_axis=new b2Vec2();const b2_minPulleyLength=2;class b2PulleyJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_pulleyJoint);this.groundAnchorA=new b2Vec2(-1,1);this.groundAnchorB=new b2Vec2(1,1);this.localAnchorA=new b2Vec2(-1,0);this.localAnchorB=new b2Vec2(1,0);this.lengthA=0;this.lengthB=0;this.ratio=1;this.collideConnected=true;}Initialize(bA,bB,groundA,groundB,anchorA,anchorB,r){this.bodyA=bA;this.bodyB=bB;this.groundAnchorA.Copy(groundA);this.groundAnchorB.Copy(groundB);this.bodyA.GetLocalPoint(anchorA,this.localAnchorA);this.bodyB.GetLocalPoint(anchorB,this.localAnchorB);this.lengthA=b2Vec2.DistanceVV(anchorA,groundA);this.lengthB=b2Vec2.DistanceVV(anchorB,groundB);this.ratio=r;}}class b2PulleyJoint extends b2Joint{constructor(def){super(def);this.m_groundAnchorA=new b2Vec2();this.m_groundAnchorB=new b2Vec2();this.m_lengthA=0;this.m_lengthB=0;this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_constant=0;this.m_ratio=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_uA=new b2Vec2();this.m_uB=new b2Vec2();this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA,new b2Vec2(-1,1)));this.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB,new b2Vec2(1,0)));this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));this.m_lengthA=b2Maybe(def.lengthA,0);this.m_lengthB=b2Maybe(def.lengthB,0);this.m_ratio=b2Maybe(def.ratio,1);this.m_constant=b2Maybe(def.lengthA,0)+this.m_ratio*b2Maybe(def.lengthB,0);this.m_impulse=0;}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_uA.Copy(cA).SelfAdd(this.m_rA).SelfSub(this.m_groundAnchorA);this.m_uB.Copy(cB).SelfAdd(this.m_rB).SelfSub(this.m_groundAnchorB);const lengthA=this.m_uA.Length();const lengthB=this.m_uB.Length();if(lengthA>10*b2_linearSlop){this.m_uA.SelfMul(1/lengthA);}else {this.m_uA.SetZero();}if(lengthB>10*b2_linearSlop){this.m_uB.SelfMul(1/lengthB);}else {this.m_uB.SetZero();}const ruA=b2Vec2.CrossVV(this.m_rA,this.m_uA);const ruB=b2Vec2.CrossVV(this.m_rB,this.m_uB);const mA=this.m_invMassA+this.m_invIA*ruA*ruA;const mB=this.m_invMassB+this.m_invIB*ruB*ruB;this.m_mass=mA+this.m_ratio*this.m_ratio*mB;if(this.m_mass>0){this.m_mass=1/this.m_mass;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const PA=b2Vec2.MulSV(-this.m_impulse,this.m_uA,b2PulleyJoint.InitVelocityConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*this.m_impulse,this.m_uB,b2PulleyJoint.InitVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2PulleyJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2PulleyJoint.SolveVelocityConstraints_s_vpB);const Cdot=-b2Vec2.DotVV(this.m_uA,vpA)-this.m_ratio*b2Vec2.DotVV(this.m_uB,vpB);const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;const PA=b2Vec2.MulSV(-impulse,this.m_uA,b2PulleyJoint.SolveVelocityConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*impulse,this.m_uB,b2PulleyJoint.SolveVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const uA=this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA);const uB=this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB);const lengthA=uA.Length();const lengthB=uB.Length();if(lengthA>10*b2_linearSlop){uA.SelfMul(1/lengthA);}else {uA.SetZero();}if(lengthB>10*b2_linearSlop){uB.SelfMul(1/lengthB);}else {uB.SetZero();}const ruA=b2Vec2.CrossVV(rA,uA);const ruB=b2Vec2.CrossVV(rB,uB);const mA=this.m_invMassA+this.m_invIA*ruA*ruA;const mB=this.m_invMassB+this.m_invIB*ruB*ruB;let mass=mA+this.m_ratio*this.m_ratio*mB;if(mass>0){mass=1/mass;}const C=this.m_constant-lengthA-this.m_ratio*lengthB;const linearError=b2Abs(C);const impulse=-mass*C;const PA=b2Vec2.MulSV(-impulse,uA,b2PulleyJoint.SolvePositionConstraints_s_PA);const PB=b2Vec2.MulSV(-this.m_ratio*impulse,uB,b2PulleyJoint.SolvePositionConstraints_s_PB);cA.SelfMulAdd(this.m_invMassA,PA);aA+=this.m_invIA*b2Vec2.CrossVV(rA,PA);cB.SelfMulAdd(this.m_invMassB,PB);aB+=this.m_invIB*b2Vec2.CrossVV(rB,PB);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError<b2_linearSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse*this.m_uB.x;out.y=inv_dt*this.m_impulse*this.m_uB.y;return out;}GetReactionTorque(inv_dt){return 0;}GetGroundAnchorA(){return this.m_groundAnchorA;}GetGroundAnchorB(){return this.m_groundAnchorB;}GetLengthA(){return this.m_lengthA;}GetLengthB(){return this.m_lengthB;}GetRatio(){return this.m_ratio;}GetCurrentLengthA(){const p=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PulleyJoint.GetCurrentLengthA_s_p);const s=this.m_groundAnchorA;return b2Vec2.DistanceVV(p,s);}GetCurrentLengthB(){const p=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PulleyJoint.GetCurrentLengthB_s_p);const s=this.m_groundAnchorB;return b2Vec2.DistanceVV(p,s);}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2PulleyJointDef = new b2PulleyJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.groundAnchorA.Set(%.15f, %.15f);\n",this.m_groundAnchorA.x,this.m_groundAnchorA.y);log("  jd.groundAnchorB.Set(%.15f, %.15f);\n",this.m_groundAnchorB.x,this.m_groundAnchorB.y);log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.lengthA = %.15f;\n",this.m_lengthA);log("  jd.lengthB = %.15f;\n",this.m_lengthB);log("  jd.ratio = %.15f;\n",this.m_ratio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}ShiftOrigin(newOrigin){this.m_groundAnchorA.SelfSub(newOrigin);this.m_groundAnchorB.SelfSub(newOrigin);}}b2PulleyJoint.InitVelocityConstraints_s_PA=new b2Vec2();b2PulleyJoint.InitVelocityConstraints_s_PB=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_PA=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_PB=new b2Vec2();b2PulleyJoint.SolvePositionConstraints_s_PA=new b2Vec2();b2PulleyJoint.SolvePositionConstraints_s_PB=new b2Vec2();b2PulleyJoint.GetCurrentLengthA_s_p=new b2Vec2();b2PulleyJoint.GetCurrentLengthB_s_p=new b2Vec2();class b2RevoluteJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_revoluteJoint);this.localAnchorA=new b2Vec2(0,0);this.localAnchorB=new b2Vec2(0,0);this.referenceAngle=0;this.enableLimit=false;this.lowerAngle=0;this.upperAngle=0;this.enableMotor=false;this.motorSpeed=0;this.maxMotorTorque=0;}Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();}}class b2RevoluteJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_impulse=new b2Vec3();this.m_motorImpulse=0;this.m_enableMotor=false;this.m_maxMotorTorque=0;this.m_motorSpeed=0;this.m_enableLimit=false;this.m_referenceAngle=0;this.m_lowerAngle=0;this.m_upperAngle=0;this.m_indexA=0;this.m_indexB=0;this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=new b2Mat33();this.m_motorMass=0;this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_K=new b2Mat22();this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_referenceAngle=b2Maybe(def.referenceAngle,0);this.m_impulse.SetZero();this.m_motorImpulse=0;this.m_lowerAngle=b2Maybe(def.lowerAngle,0);this.m_upperAngle=b2Maybe(def.upperAngle,0);this.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);this.m_motorSpeed=b2Maybe(def.motorSpeed,0);this.m_enableLimit=b2Maybe(def.enableLimit,false);this.m_enableMotor=b2Maybe(def.enableMotor,false);this.m_limitState=exports.b2LimitState.e_inactiveLimit;}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const fixedRotation=iA+iB===0;this.m_mass.ex.x=mA+mB+this.m_rA.y*this.m_rA.y*iA+this.m_rB.y*this.m_rB.y*iB;this.m_mass.ey.x=-this.m_rA.y*this.m_rA.x*iA-this.m_rB.y*this.m_rB.x*iB;this.m_mass.ez.x=-this.m_rA.y*iA-this.m_rB.y*iB;this.m_mass.ex.y=this.m_mass.ey.x;this.m_mass.ey.y=mA+mB+this.m_rA.x*this.m_rA.x*iA+this.m_rB.x*this.m_rB.x*iB;this.m_mass.ez.y=this.m_rA.x*iA+this.m_rB.x*iB;this.m_mass.ex.z=this.m_mass.ez.x;this.m_mass.ey.z=this.m_mass.ez.y;this.m_mass.ez.z=iA+iB;this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}if(!this.m_enableMotor||fixedRotation){this.m_motorImpulse=0;}if(this.m_enableLimit&&!fixedRotation){const jointAngle=aB-aA-this.m_referenceAngle;if(b2Abs(this.m_upperAngle-this.m_lowerAngle)<2*b2_angularSlop){this.m_limitState=exports.b2LimitState.e_equalLimits;}else if(jointAngle<=this.m_lowerAngle){if(this.m_limitState!==exports.b2LimitState.e_atLowerLimit){this.m_impulse.z=0;}this.m_limitState=exports.b2LimitState.e_atLowerLimit;}else if(jointAngle>=this.m_upperAngle){if(this.m_limitState!==exports.b2LimitState.e_atUpperLimit){this.m_impulse.z=0;}this.m_limitState=exports.b2LimitState.e_atUpperLimit;}else {this.m_limitState=exports.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports.b2LimitState.e_inactiveLimit;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;const P=b2RevoluteJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_motorImpulse+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_motorImpulse+this.m_impulse.z);}else {this.m_impulse.SetZero();this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const fixedRotation=iA+iB===0;if(this.m_enableMotor&&this.m_limitState!==exports.b2LimitState.e_equalLimits&&!fixedRotation){const Cdot=wB-wA-this.m_motorSpeed;let impulse=-this.m_motorMass*Cdot;const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit&&!fixedRotation){const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1);const Cdot2=wB-wA;const impulse_v3=this.m_mass.Solve33(Cdot1.x,Cdot1.y,Cdot2,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3).SelfNeg();if(this.m_limitState===exports.b2LimitState.e_equalLimits){this.m_impulse.SelfAdd(impulse_v3);}else if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){const newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse<0){const rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;const rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;const reduced_v2=this.m_mass.Solve22(rhs_x,rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=reduced_v2.x;impulse_v3.y=reduced_v2.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=reduced_v2.x;this.m_impulse.y+=reduced_v2.y;this.m_impulse.z=0;}else {this.m_impulse.SelfAdd(impulse_v3);}}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){const newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse>0){const rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;const rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;const reduced_v2=this.m_mass.Solve22(rhs_x,rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=reduced_v2.x;impulse_v3.y=reduced_v2.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=reduced_v2.x;this.m_impulse.y+=reduced_v2.y;this.m_impulse.z=0;}else {this.m_impulse.SelfAdd(impulse_v3);}}const P=b2RevoluteJoint.SolveVelocityConstraints_s_P.Set(impulse_v3.x,impulse_v3.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse_v3.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse_v3.z);}else {const Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2);const impulse_v2=this.m_mass.Solve22(-Cdot_v2.x,-Cdot_v2.y,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2);this.m_impulse.x+=impulse_v2.x;this.m_impulse.y+=impulse_v2.y;vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulse_v2);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);let angularError=0;let positionError=0;const fixedRotation=this.m_invIA+this.m_invIB===0;if(this.m_enableLimit&&this.m_limitState!==exports.b2LimitState.e_inactiveLimit&&!fixedRotation){const angle=aB-aA-this.m_referenceAngle;let limitImpulse=0;if(this.m_limitState===exports.b2LimitState.e_equalLimits){const C=b2Clamp(angle-this.m_lowerAngle,-b2_maxAngularCorrection,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=b2Abs(C);}else if(this.m_limitState===exports.b2LimitState.e_atLowerLimit){let C=angle-this.m_lowerAngle;angularError=-C;C=b2Clamp(C+b2_angularSlop,-b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*C;}else if(this.m_limitState===exports.b2LimitState.e_atUpperLimit){let C=angle-this.m_upperAngle;angularError=C;C=b2Clamp(C-b2_angularSlop,0,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;}aA-=this.m_invIA*limitImpulse;aB+=this.m_invIB*limitImpulse;}{qA.SetAngle(aA);qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const C_v2=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2RevoluteJoint.SolvePositionConstraints_s_C_v2);positionError=C_v2.Length();const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;const impulse=K.Solve(C_v2.x,C_v2.y,b2RevoluteJoint.SolvePositionConstraints_s_impulse).SelfNeg();cA.SelfMulSub(mA,impulse);aA-=iA*b2Vec2.CrossVV(rA,impulse);cB.SelfMulAdd(mB,impulse);aB+=iB*b2Vec2.CrossVV(rB,impulse);}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}GetReferenceAngle(){return this.m_referenceAngle;}GetJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a-this.m_referenceAngle;}GetJointSpeed(){return this.m_bodyB.m_angularVelocity-this.m_bodyA.m_angularVelocity;}IsMotorEnabled(){return this.m_enableMotor;}EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}}GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;}GetMotorSpeed(){return this.m_motorSpeed;}SetMaxMotorTorque(torque){if(torque!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=torque;}}GetMaxMotorTorque(){return this.m_maxMotorTorque;}IsLimitEnabled(){return this.m_enableLimit;}EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0;}}GetLowerLimit(){return this.m_lowerAngle;}GetUpperLimit(){return this.m_upperAngle;}SetLimits(lower,upper){if(lower!==this.m_lowerAngle||upper!==this.m_upperAngle){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_impulse.z=0;this.m_lowerAngle=lower;this.m_upperAngle=upper;}}SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2RevoluteJointDef = new b2RevoluteJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log("  jd.lowerAngle = %.15f;\n",this.m_lowerAngle);log("  jd.upperAngle = %.15f;\n",this.m_upperAngle);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2RevoluteJoint.InitVelocityConstraints_s_P=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3=new b2Vec3();b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2();b2RevoluteJoint.SolvePositionConstraints_s_C_v2=new b2Vec2();b2RevoluteJoint.SolvePositionConstraints_s_impulse=new b2Vec2();class b2RopeJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_ropeJoint);this.localAnchorA=new b2Vec2(-1,0);this.localAnchorB=new b2Vec2(1,0);this.maxLength=0;}}class b2RopeJoint extends b2Joint{constructor(def){super(def);this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_maxLength=0;this.m_length=0;this.m_impulse=0;this.m_indexA=0;this.m_indexB=0;this.m_u=new b2Vec2();this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=0;this.m_state=exports.b2LimitState.e_inactiveLimit;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));this.m_maxLength=b2Maybe(def.maxLength,0);}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.Copy(cB).SelfAdd(this.m_rB).SelfSub(cA).SelfSub(this.m_rA);this.m_length=this.m_u.Length();const C=this.m_length-this.m_maxLength;if(C>0){this.m_state=exports.b2LimitState.e_atUpperLimit;}else {this.m_state=exports.b2LimitState.e_inactiveLimit;}if(this.m_length>b2_linearSlop){this.m_u.SelfMul(1/this.m_length);}else {this.m_u.SetZero();this.m_mass=0;this.m_impulse=0;return;}const crA=b2Vec2.CrossVV(this.m_rA,this.m_u);const crB=b2Vec2.CrossVV(this.m_rB,this.m_u);const invMass=this.m_invMassA+this.m_invIA*crA*crA+this.m_invMassB+this.m_invIB*crB*crB;this.m_mass=invMass!==0?1/invMass:0;if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;const P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2RopeJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2RopeJoint.SolveVelocityConstraints_s_vpA);const vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2RopeJoint.SolveVelocityConstraints_s_vpB);const C=this.m_length-this.m_maxLength;let Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));if(C<0){Cdot+=data.step.inv_dt*C;}let impulse=-this.m_mass*Cdot;const oldImpulse=this.m_impulse;this.m_impulse=b2Min(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;const P=b2Vec2.MulSV(impulse,this.m_u,b2RopeJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const u=this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA);const length=u.Normalize();let C=length-this.m_maxLength;C=b2Clamp(C,0,b2_maxLinearCorrection);const impulse=-this.m_mass*C;const P=b2Vec2.MulSV(impulse,u,b2RopeJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return length-this.m_maxLength<b2_linearSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_u,out);}GetReactionTorque(inv_dt){return 0;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}SetMaxLength(length){this.m_maxLength=length;}GetMaxLength(){return this.m_maxLength;}GetLimitState(){return this.m_state;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2RopeJointDef = new b2RopeJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.maxLength = %.15f;\n",this.m_maxLength);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2RopeJoint.InitVelocityConstraints_s_P=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2RopeJoint.SolvePositionConstraints_s_P=new b2Vec2();class b2WeldJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_weldJoint);this.localAnchorA=new b2Vec2();this.localAnchorB=new b2Vec2();this.referenceAngle=0;this.frequencyHz=0;this.dampingRatio=0;}Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();}}class b2WeldJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_bias=0;this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_referenceAngle=0;this.m_gamma=0;this.m_impulse=new b2Vec3(0,0,0);this.m_indexA=0;this.m_indexB=0;this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_mass=new b2Mat33();this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_K=new b2Mat33();this.m_frequencyHz=b2Maybe(def.frequencyHz,0);this.m_dampingRatio=b2Maybe(def.dampingRatio,0);this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_referenceAngle=b2Maybe(def.referenceAngle,0);this.m_impulse.SetZero();}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const K=this.m_K;K.ex.x=mA+mB+this.m_rA.y*this.m_rA.y*iA+this.m_rB.y*this.m_rB.y*iB;K.ey.x=-this.m_rA.y*this.m_rA.x*iA-this.m_rB.y*this.m_rB.x*iB;K.ez.x=-this.m_rA.y*iA-this.m_rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+this.m_rA.x*this.m_rA.x*iA+this.m_rB.x*this.m_rB.x*iB;K.ez.y=this.m_rA.x*iA+this.m_rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){K.GetInverse22(this.m_mass);let invM=iA+iB;const m=invM>0?1/invM:0;const C=aB-aA-this.m_referenceAngle;const omega=2*b2_pi*this.m_frequencyHz;const d=2*m*this.m_dampingRatio*omega;const k=m*omega*omega;const h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invM+=this.m_gamma;this.m_mass.ez.z=invM!==0?1/invM:0;}else {K.GetSymInverse33(this.m_mass);this.m_gamma=0;this.m_bias=0;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);const P=b2WeldJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_impulse.z);}else {this.m_impulse.SetZero();}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;if(this.m_frequencyHz>0){const Cdot2=wB-wA;const impulse2=-this.m_mass.ez.z*(Cdot2+this.m_bias+this.m_gamma*this.m_impulse.z);this.m_impulse.z+=impulse2;wA-=iA*impulse2;wB+=iB*impulse2;const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);const impulse1=b2Mat33.MulM33XY(this.m_mass,Cdot1.x,Cdot1.y,b2WeldJoint.SolveVelocityConstraints_s_impulse1).SelfNeg();this.m_impulse.x+=impulse1.x;this.m_impulse.y+=impulse1.y;const P=impulse1;vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(this.m_rB,P);}else {const Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);const Cdot2=wB-wA;const impulse=b2Mat33.MulM33XYZ(this.m_mass,Cdot1.x,Cdot1.y,Cdot2,b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg();this.m_impulse.SelfAdd(impulse);const P=b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x,impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse.z);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);let positionError,angularError;const K=this.m_K;K.ex.x=mA+mB+rA.y*rA.y*iA+rB.y*rB.y*iB;K.ey.x=-rA.y*rA.x*iA-rB.y*rB.x*iB;K.ez.x=-rA.y*iA-rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+rA.x*rA.x*iA+rB.x*rB.x*iB;K.ez.y=rA.x*iA+rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){const C1=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);positionError=C1.Length();angularError=0;const P=K.Solve22(C1.x,C1.y,b2WeldJoint.SolvePositionConstraints_s_P).SelfNeg();cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}else {const C1=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);const C2=aB-aA-this.m_referenceAngle;positionError=C1.Length();angularError=b2Abs(C2);const impulse=K.Solve33(C1.x,C1.y,C2,b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg();const P=b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x,impulse.y);cA.SelfMulSub(mA,P);aA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse.z);cB.SelfMulAdd(mB,P);aB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse.z);}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;}GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}GetReferenceAngle(){return this.m_referenceAngle;}SetFrequency(hz){this.m_frequencyHz=hz;}GetFrequency(){return this.m_frequencyHz;}SetDampingRatio(ratio){this.m_dampingRatio=ratio;}GetDampingRatio(){return this.m_dampingRatio;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2WeldJointDef = new b2WeldJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2WeldJoint.InitVelocityConstraints_s_P=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_impulse1=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_impulse=new b2Vec3();b2WeldJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_C1=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_P=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_impulse=new b2Vec3();class b2WheelJointDef extends b2JointDef{constructor(){super(exports.b2JointType.e_wheelJoint);this.localAnchorA=new b2Vec2(0,0);this.localAnchorB=new b2Vec2(0,0);this.localAxisA=new b2Vec2(1,0);this.enableMotor=false;this.maxMotorTorque=0;this.motorSpeed=0;this.frequencyHz=2;this.dampingRatio=0.7;}Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA);}}class b2WheelJoint extends b2Joint{constructor(def){super(def);this.m_frequencyHz=0;this.m_dampingRatio=0;this.m_localAnchorA=new b2Vec2();this.m_localAnchorB=new b2Vec2();this.m_localXAxisA=new b2Vec2();this.m_localYAxisA=new b2Vec2();this.m_impulse=0;this.m_motorImpulse=0;this.m_springImpulse=0;this.m_maxMotorTorque=0;this.m_motorSpeed=0;this.m_enableMotor=false;this.m_indexA=0;this.m_indexB=0;this.m_localCenterA=new b2Vec2();this.m_localCenterB=new b2Vec2();this.m_invMassA=0;this.m_invMassB=0;this.m_invIA=0;this.m_invIB=0;this.m_ax=new b2Vec2();this.m_ay=new b2Vec2();this.m_sAx=0;this.m_sBx=0;this.m_sAy=0;this.m_sBy=0;this.m_mass=0;this.m_motorMass=0;this.m_springMass=0;this.m_bias=0;this.m_gamma=0;this.m_qA=new b2Rot();this.m_qB=new b2Rot();this.m_lalcA=new b2Vec2();this.m_lalcB=new b2Vec2();this.m_rA=new b2Vec2();this.m_rB=new b2Vec2();this.m_frequencyHz=b2Maybe(def.frequencyHz,2);this.m_dampingRatio=b2Maybe(def.dampingRatio,0.7);this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));this.m_localXAxisA.Copy(b2Maybe(def.localAxisA,b2Vec2.UNITX));b2Vec2.CrossOneV(this.m_localXAxisA,this.m_localYAxisA);this.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);this.m_motorSpeed=b2Maybe(def.motorSpeed,0);this.m_enableMotor=b2Maybe(def.enableMotor,false);this.m_ax.SetZero();this.m_ay.SetZero();}GetMotorSpeed(){return this.m_motorSpeed;}GetMaxMotorTorque(){return this.m_maxMotorTorque;}SetSpringFrequencyHz(hz){this.m_frequencyHz=hz;}GetSpringFrequencyHz(){return this.m_frequencyHz;}SetSpringDampingRatio(ratio){this.m_dampingRatio=ratio;}GetSpringDampingRatio(){return this.m_dampingRatio;}InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const cA=data.positions[this.m_indexA].c;const aA=data.positions[this.m_indexA].a;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const cB=data.positions[this.m_indexB].c;const aB=data.positions[this.m_indexB].a;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_d);{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);this.m_sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ay);this.m_sBy=b2Vec2.CrossVV(rB,this.m_ay);this.m_mass=mA+mB+iA*this.m_sAy*this.m_sAy+iB*this.m_sBy*this.m_sBy;if(this.m_mass>0){this.m_mass=1/this.m_mass;}}this.m_springMass=0;this.m_bias=0;this.m_gamma=0;if(this.m_frequencyHz>0){b2Rot.MulRV(qA,this.m_localXAxisA,this.m_ax);this.m_sAx=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ax);this.m_sBx=b2Vec2.CrossVV(rB,this.m_ax);const invMass=mA+mB+iA*this.m_sAx*this.m_sAx+iB*this.m_sBx*this.m_sBx;if(invMass>0){this.m_springMass=1/invMass;const C=b2Vec2.DotVV(d,this.m_ax);const omega=2*b2_pi*this.m_frequencyHz;const damp=2*this.m_springMass*this.m_dampingRatio*omega;const k=this.m_springMass*omega*omega;const h=data.step.dt;this.m_gamma=h*(damp+h*k);if(this.m_gamma>0){this.m_gamma=1/this.m_gamma;}this.m_bias=C*h*k*this.m_gamma;this.m_springMass=invMass+this.m_gamma;if(this.m_springMass>0){this.m_springMass=1/this.m_springMass;}}}else {this.m_springImpulse=0;}if(this.m_enableMotor){this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}}else {this.m_motorMass=0;this.m_motorImpulse=0;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;this.m_springImpulse*=data.step.dtRatio;this.m_motorImpulse*=data.step.dtRatio;const P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse,this.m_ay,b2Vec2.s_t0),b2Vec2.MulSV(this.m_springImpulse,this.m_ax,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_P);const LA=this.m_impulse*this.m_sAy+this.m_springImpulse*this.m_sAx+this.m_motorImpulse;const LB=this.m_impulse*this.m_sBy+this.m_springImpulse*this.m_sBx+this.m_motorImpulse;vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*LA;vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*LB;}else {this.m_impulse=0;this.m_springImpulse=0;this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolveVelocityConstraints(data){const mA=this.m_invMassA,mB=this.m_invMassB;const iA=this.m_invIA,iB=this.m_invIB;const vA=data.velocities[this.m_indexA].v;let wA=data.velocities[this.m_indexA].w;const vB=data.velocities[this.m_indexB].v;let wB=data.velocities[this.m_indexB].w;{const Cdot=b2Vec2.DotVV(this.m_ax,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBx*wB-this.m_sAx*wA;const impulse=-this.m_springMass*(Cdot+this.m_bias+this.m_gamma*this.m_springImpulse);this.m_springImpulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_ax,b2WheelJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_sAx;const LB=impulse*this.m_sBx;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}{const Cdot=wB-wA-this.m_motorSpeed;let impulse=-this.m_motorMass*Cdot;const oldImpulse=this.m_motorImpulse;const maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}{const Cdot=b2Vec2.DotVV(this.m_ay,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBy*wB-this.m_sAy*wA;const impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;const P=b2Vec2.MulSV(impulse,this.m_ay,b2WheelJoint.SolveVelocityConstraints_s_P);const LA=impulse*this.m_sAy;const LB=impulse*this.m_sBy;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;}SolvePositionConstraints(data){const cA=data.positions[this.m_indexA].c;let aA=data.positions[this.m_indexA].a;const cB=data.positions[this.m_indexB].c;let aB=data.positions[this.m_indexB].a;const qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);const rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);const rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);const d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2WheelJoint.SolvePositionConstraints_s_d);const ay=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);const sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),ay);const sBy=b2Vec2.CrossVV(rB,ay);const C=b2Vec2.DotVV(d,this.m_ay);const k=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_sAy*this.m_sAy+this.m_invIB*this.m_sBy*this.m_sBy;let impulse;if(k!==0){impulse=-C/k;}else {impulse=0;}const P=b2Vec2.MulSV(impulse,ay,b2WheelJoint.SolvePositionConstraints_s_P);const LA=impulse*sAy;const LB=impulse*sBy;cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*LA;cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)<=b2_linearSlop;}GetDefinition(def){return def;}GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);}GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);}GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse*this.m_ay.x+this.m_springImpulse*this.m_ax.x);out.y=inv_dt*(this.m_impulse*this.m_ay.y+this.m_springImpulse*this.m_ax.y);return out;}GetReactionTorque(inv_dt){return inv_dt*this.m_motorImpulse;}GetLocalAnchorA(){return this.m_localAnchorA;}GetLocalAnchorB(){return this.m_localAnchorB;}GetLocalAxisA(){return this.m_localXAxisA;}GetJointTranslation(){return this.GetPrismaticJointTranslation();}GetJointLinearSpeed(){return this.GetPrismaticJointSpeed();}GetJointAngle(){return this.GetRevoluteJointAngle();}GetJointAngularSpeed(){return this.GetRevoluteJointSpeed();}GetPrismaticJointTranslation(){const bA=this.m_bodyA;const bB=this.m_bodyB;const pA=bA.GetWorldPoint(this.m_localAnchorA,new b2Vec2());const pB=bB.GetWorldPoint(this.m_localAnchorB,new b2Vec2());const d=b2Vec2.SubVV(pB,pA,new b2Vec2());const axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());const translation=b2Vec2.DotVV(d,axis);return translation;}GetPrismaticJointSpeed(){const bA=this.m_bodyA;const bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);const rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);const rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);const pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);const pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);const d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);const axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());const vA=bA.m_linearVelocity;const vB=bB.m_linearVelocity;const wA=bA.m_angularVelocity;const wB=bB.m_angularVelocity;const speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed;}GetRevoluteJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a;}GetRevoluteJointSpeed(){const wA=this.m_bodyA.m_angularVelocity;const wB=this.m_bodyB.m_angularVelocity;return wB-wA;}IsMotorEnabled(){return this.m_enableMotor;}EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}}SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}}SetMaxMotorTorque(force){if(force!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=force;}}GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;}Dump(log){const indexA=this.m_bodyA.m_islandIndex;const indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2WheelJointDef = new b2WheelJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);}}b2WheelJoint.InitVelocityConstraints_s_d=new b2Vec2();b2WheelJoint.InitVelocityConstraints_s_P=new b2Vec2();b2WheelJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2WheelJoint.SolvePositionConstraints_s_d=new b2Vec2();b2WheelJoint.SolvePositionConstraints_s_P=new b2Vec2();function b2MixFriction(friction1,friction2){return b2Sqrt(friction1*friction2);}function b2MixRestitution(restitution1,restitution2){return restitution1>restitution2?restitution1:restitution2;}class b2ContactEdge{constructor(contact){this._other=null;this.prev=null;this.next=null;this.contact=contact;}get other(){if(this._other===null){throw new Error();}return this._other;}set other(value){if(this._other!==null){throw new Error();}this._other=value;}Reset(){this._other=null;this.prev=null;this.next=null;}}class b2Contact{constructor(){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=false;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_prev=null;this.m_next=null;this.m_nodeA=new b2ContactEdge(this);this.m_nodeB=new b2ContactEdge(this);this.m_indexA=0;this.m_indexB=0;this.m_manifold=new b2Manifold();this.m_toiCount=0;this.m_toi=0;this.m_friction=0;this.m_restitution=0;this.m_tangentSpeed=0;this.m_oldManifold=new b2Manifold();}GetManifold(){return this.m_manifold;}GetWorldManifold(worldManifold){const bodyA=this.m_fixtureA.GetBody();const bodyB=this.m_fixtureB.GetBody();const shapeA=this.GetShapeA();const shapeB=this.GetShapeB();worldManifold.Initialize(this.m_manifold,bodyA.GetTransform(),shapeA.m_radius,bodyB.GetTransform(),shapeB.m_radius);}IsTouching(){return this.m_touchingFlag;}SetEnabled(flag){this.m_enabledFlag=flag;}IsEnabled(){return this.m_enabledFlag;}GetNext(){return this.m_next;}GetFixtureA(){return this.m_fixtureA;}GetChildIndexA(){return this.m_indexA;}GetShapeA(){return this.m_fixtureA.GetShape();}GetFixtureB(){return this.m_fixtureB;}GetChildIndexB(){return this.m_indexB;}GetShapeB(){return this.m_fixtureB.GetShape();}FlagForFiltering(){this.m_filterFlag=true;}SetFriction(friction){this.m_friction=friction;}GetFriction(){return this.m_friction;}ResetFriction(){this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);}SetRestitution(restitution){this.m_restitution=restitution;}GetRestitution(){return this.m_restitution;}ResetRestitution(){this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution);}SetTangentSpeed(speed){this.m_tangentSpeed=speed;}GetTangentSpeed(){return this.m_tangentSpeed;}Reset(fixtureA,indexA,fixtureB,indexB){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=true;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.m_indexA=indexA;this.m_indexB=indexB;this.m_manifold.pointCount=0;this.m_prev=null;this.m_next=null;this.m_nodeA.Reset();this.m_nodeB.Reset();this.m_toiCount=0;this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution);}Update(listener){const tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.m_enabledFlag=true;let touching=false;const wasTouching=this.m_touchingFlag;const sensorA=this.m_fixtureA.IsSensor();const sensorB=this.m_fixtureB.IsSensor();const sensor=sensorA||sensorB;const bodyA=this.m_fixtureA.GetBody();const bodyB=this.m_fixtureB.GetBody();const xfA=bodyA.GetTransform();const xfB=bodyB.GetTransform();if(sensor){const shapeA=this.GetShapeA();const shapeB=this.GetShapeB();touching=b2TestOverlapShape(shapeA,this.m_indexA,shapeB,this.m_indexB,xfA,xfB);this.m_manifold.pointCount=0;}else {this.Evaluate(this.m_manifold,xfA,xfB);touching=this.m_manifold.pointCount>0;for(let i=0;i<this.m_manifold.pointCount;++i){const mp2=this.m_manifold.points[i];mp2.normalImpulse=0;mp2.tangentImpulse=0;const id2=mp2.id;for(let j=0;j<this.m_oldManifold.pointCount;++j){const mp1=this.m_oldManifold.points[j];if(mp1.id.key===id2.key){mp2.normalImpulse=mp1.normalImpulse;mp2.tangentImpulse=mp1.tangentImpulse;break;}}}if(touching!==wasTouching){bodyA.SetAwake(true);bodyB.SetAwake(true);}}this.m_touchingFlag=touching;if(!wasTouching&&touching&&listener){listener.BeginContact(this);}if(wasTouching&&!touching&&listener){listener.EndContact(this);}if(!sensor&&touching&&listener){listener.PreSolve(this,this.m_oldManifold);}}ComputeTOI(sweepA,sweepB){const input=b2Contact.ComputeTOI_s_input;input.proxyA.SetShape(this.GetShapeA(),this.m_indexA);input.proxyB.SetShape(this.GetShapeB(),this.m_indexB);input.sweepA.Copy(sweepA);input.sweepB.Copy(sweepB);input.tMax=b2_linearSlop;const output=b2Contact.ComputeTOI_s_output;b2TimeOfImpact(output,input);return output.t;}}b2Contact.ComputeTOI_s_input=new b2TOIInput();b2Contact.ComputeTOI_s_output=new b2TOIOutput();class b2CircleContact extends b2Contact{static Create(){return new b2CircleContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){b2CollideCircles(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);}}class b2PolygonContact extends b2Contact{static Create(){return new b2PolygonContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){b2CollidePolygons(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);}}class b2PolygonAndCircleContact extends b2Contact{static Create(){return new b2PolygonAndCircleContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){b2CollidePolygonAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);}}class b2EdgeAndCircleContact extends b2Contact{static Create(){return new b2EdgeAndCircleContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){b2CollideEdgeAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);}}class b2EdgeAndPolygonContact extends b2Contact{static Create(){return new b2EdgeAndPolygonContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){b2CollideEdgeAndPolygon(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);}}class b2ChainAndCircleContact extends b2Contact{static Create(){return new b2ChainAndCircleContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){const edge=b2ChainAndCircleContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndCircle(manifold,edge,xfA,this.GetShapeB(),xfB);}}b2ChainAndCircleContact.Evaluate_s_edge=new b2EdgeShape();class b2ChainAndPolygonContact extends b2Contact{static Create(){return new b2ChainAndPolygonContact();}static Destroy(contact){}Evaluate(manifold,xfA,xfB){const edge=b2ChainAndPolygonContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndPolygon(manifold,edge,xfA,this.GetShapeB(),xfB);}}b2ChainAndPolygonContact.Evaluate_s_edge=new b2EdgeShape();class b2ContactRegister{constructor(){this.pool=[];this.createFcn=null;this.destroyFcn=null;this.primary=false;}}class b2ContactFactory{constructor(){this.m_registers=[];this.InitializeRegisters();}AddType(createFcn,destroyFcn,typeA,typeB){const pool=[];function poolCreateFcn(){return pool.pop()||createFcn();}function poolDestroyFcn(contact){pool.push(contact);}this.m_registers[typeA][typeB].pool=pool;this.m_registers[typeA][typeB].createFcn=poolCreateFcn;this.m_registers[typeA][typeB].destroyFcn=poolDestroyFcn;this.m_registers[typeA][typeB].primary=true;if(typeA!==typeB){this.m_registers[typeB][typeA].pool=pool;this.m_registers[typeB][typeA].createFcn=poolCreateFcn;this.m_registers[typeB][typeA].destroyFcn=poolDestroyFcn;this.m_registers[typeB][typeA].primary=false;}}InitializeRegisters(){for(let i=0;i<exports.b2ShapeType.e_shapeTypeCount;i++){this.m_registers[i]=[];for(let j=0;j<exports.b2ShapeType.e_shapeTypeCount;j++){this.m_registers[i][j]=new b2ContactRegister();}}this.AddType(b2CircleContact.Create,b2CircleContact.Destroy,exports.b2ShapeType.e_circleShape,exports.b2ShapeType.e_circleShape);this.AddType(b2PolygonAndCircleContact.Create,b2PolygonAndCircleContact.Destroy,exports.b2ShapeType.e_polygonShape,exports.b2ShapeType.e_circleShape);this.AddType(b2PolygonContact.Create,b2PolygonContact.Destroy,exports.b2ShapeType.e_polygonShape,exports.b2ShapeType.e_polygonShape);this.AddType(b2EdgeAndCircleContact.Create,b2EdgeAndCircleContact.Destroy,exports.b2ShapeType.e_edgeShape,exports.b2ShapeType.e_circleShape);this.AddType(b2EdgeAndPolygonContact.Create,b2EdgeAndPolygonContact.Destroy,exports.b2ShapeType.e_edgeShape,exports.b2ShapeType.e_polygonShape);this.AddType(b2ChainAndCircleContact.Create,b2ChainAndCircleContact.Destroy,exports.b2ShapeType.e_chainShape,exports.b2ShapeType.e_circleShape);this.AddType(b2ChainAndPolygonContact.Create,b2ChainAndPolygonContact.Destroy,exports.b2ShapeType.e_chainShape,exports.b2ShapeType.e_polygonShape);}Create(fixtureA,indexA,fixtureB,indexB){const typeA=fixtureA.GetType();const typeB=fixtureB.GetType();const reg=this.m_registers[typeA][typeB];if(reg.createFcn){const c=reg.createFcn();if(reg.primary){c.Reset(fixtureA,indexA,fixtureB,indexB);}else {c.Reset(fixtureB,indexB,fixtureA,indexA);}return c;}else {return null;}}Destroy(contact){const typeA=contact.m_fixtureA.GetType();const typeB=contact.m_fixtureB.GetType();const reg=this.m_registers[typeA][typeB];if(reg.destroyFcn){reg.destroyFcn(contact);}}}class b2DestructionListener{SayGoodbyeJoint(joint){}SayGoodbyeFixture(fixture){}SayGoodbyeParticleGroup(group){}SayGoodbyeParticle(system,index){}}class b2ContactFilter{ShouldCollide(fixtureA,fixtureB){const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(bodyB.GetType()===exports.b2BodyType.b2_staticBody&&bodyA.GetType()===exports.b2BodyType.b2_staticBody){return false;}if(!bodyB.ShouldCollideConnected(bodyA)){return false;}const filter1=fixtureA.GetFilterData();const filter2=fixtureB.GetFilterData();if(filter1.groupIndex===filter2.groupIndex&&filter1.groupIndex!==0){return filter1.groupIndex>0;}const collide=(filter1.maskBits&filter2.categoryBits)!==0&&(filter1.categoryBits&filter2.maskBits)!==0;return collide;}ShouldCollideFixtureParticle(fixture,system,index){return true;}ShouldCollideParticleParticle(system,indexA,indexB){return true;}}b2ContactFilter.b2_defaultFilter=new b2ContactFilter();class b2ContactImpulse{constructor(){this.normalImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.tangentImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.count=0;}}class b2ContactListener{BeginContact(contact){}EndContact(contact){}BeginContactFixtureParticle(system,contact){}EndContactFixtureParticle(system,contact){}BeginContactParticleParticle(system,contact){}EndContactParticleParticle(system,contact){}PreSolve(contact,oldManifold){}PostSolve(contact,impulse){}}b2ContactListener.b2_defaultListener=new b2ContactListener();class b2QueryCallback{ReportFixture(fixture){return true;}ReportParticle(system,index){return false;}ShouldQueryParticleSystem(system){return true;}}class b2RayCastCallback{ReportFixture(fixture,point,normal,fraction){return fraction;}ReportParticle(system,index,point,normal,fraction){return 0;}ShouldQueryParticleSystem(system){return true;}}class b2ContactManager{constructor(){this.m_broadPhase=new b2BroadPhase();this.m_contactList=null;this.m_contactCount=0;this.m_contactFilter=b2ContactFilter.b2_defaultFilter;this.m_contactListener=b2ContactListener.b2_defaultListener;this.m_contactFactory=new b2ContactFactory();}AddPair(proxyA,proxyB){let fixtureA=proxyA.fixture;let fixtureB=proxyB.fixture;let indexA=proxyA.childIndex;let indexB=proxyB.childIndex;let bodyA=fixtureA.GetBody();let bodyB=fixtureB.GetBody();if(bodyA===bodyB){return;}let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){const fA=edge.contact.GetFixtureA();const fB=edge.contact.GetFixtureB();const iA=edge.contact.GetChildIndexA();const iB=edge.contact.GetChildIndexB();if(fA===fixtureA&&fB===fixtureB&&iA===indexA&&iB===indexB){return;}if(fA===fixtureB&&fB===fixtureA&&iA===indexB&&iB===indexA){return;}}edge=edge.next;}if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){return;}const c=this.m_contactFactory.Create(fixtureA,indexA,fixtureB,indexB);if(c===null){return;}fixtureA=c.GetFixtureA();fixtureB=c.GetFixtureB();indexA=c.GetChildIndexA();indexB=c.GetChildIndexB();bodyA=fixtureA.m_body;bodyB=fixtureB.m_body;c.m_prev=null;c.m_next=this.m_contactList;if(this.m_contactList!==null){this.m_contactList.m_prev=c;}this.m_contactList=c;c.m_nodeA.other=bodyB;c.m_nodeA.prev=null;c.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!==null){bodyA.m_contactList.prev=c.m_nodeA;}bodyA.m_contactList=c.m_nodeA;c.m_nodeB.other=bodyA;c.m_nodeB.prev=null;c.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!==null){bodyB.m_contactList.prev=c.m_nodeB;}bodyB.m_contactList=c.m_nodeB;if(!fixtureA.IsSensor()&&!fixtureB.IsSensor()){bodyA.SetAwake(true);bodyB.SetAwake(true);}++this.m_contactCount;}FindNewContacts(){this.m_broadPhase.UpdatePairs((proxyA,proxyB)=>{this.AddPair(proxyA,proxyB);});}Destroy(c){const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(this.m_contactListener&&c.IsTouching()){this.m_contactListener.EndContact(c);}if(c.m_prev){c.m_prev.m_next=c.m_next;}if(c.m_next){c.m_next.m_prev=c.m_prev;}if(c===this.m_contactList){this.m_contactList=c.m_next;}if(c.m_nodeA.prev){c.m_nodeA.prev.next=c.m_nodeA.next;}if(c.m_nodeA.next){c.m_nodeA.next.prev=c.m_nodeA.prev;}if(c.m_nodeA===bodyA.m_contactList){bodyA.m_contactList=c.m_nodeA.next;}if(c.m_nodeB.prev){c.m_nodeB.prev.next=c.m_nodeB.next;}if(c.m_nodeB.next){c.m_nodeB.next.prev=c.m_nodeB.prev;}if(c.m_nodeB===bodyB.m_contactList){bodyB.m_contactList=c.m_nodeB.next;}if(c.m_manifold.pointCount>0&&!fixtureA.IsSensor()&&!fixtureB.IsSensor()){fixtureA.GetBody().SetAwake(true);fixtureB.GetBody().SetAwake(true);}this.m_contactFactory.Destroy(c);--this.m_contactCount;}Collide(){let c=this.m_contactList;while(c){const fixtureA=c.GetFixtureA();const fixtureB=c.GetFixtureB();const indexA=c.GetChildIndexA();const indexB=c.GetChildIndexB();const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();if(c.m_filterFlag){if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){const cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue;}c.m_filterFlag=false;}const activeA=bodyA.IsAwake()&&bodyA.m_type!==exports.b2BodyType.b2_staticBody;const activeB=bodyB.IsAwake()&&bodyB.m_type!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){c=c.m_next;continue;}const treeNodeA=fixtureA.m_proxies[indexA].treeNode;const treeNodeB=fixtureB.m_proxies[indexB].treeNode;const overlap=b2TestOverlapAABB(treeNodeA.aabb,treeNodeB.aabb);if(!overlap){const cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue;}c.Update(this.m_contactListener);c=c.m_next;}}}class b2Profile{constructor(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;}Reset(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;return this;}}class b2TimeStep{constructor(){this.dt=0;this.inv_dt=0;this.dtRatio=0;this.velocityIterations=0;this.positionIterations=0;this.particleIterations=0;this.warmStarting=false;}Copy(step){this.dt=step.dt;this.inv_dt=step.inv_dt;this.dtRatio=step.dtRatio;this.positionIterations=step.positionIterations;this.velocityIterations=step.velocityIterations;this.particleIterations=step.particleIterations;this.warmStarting=step.warmStarting;return this;}}class b2Position{constructor(){this.c=new b2Vec2();this.a=0;}static MakeArray(length){return b2MakeArray(length,i=>new b2Position());}}class b2Velocity{constructor(){this.v=new b2Vec2();this.w=0;}static MakeArray(length){return b2MakeArray(length,i=>new b2Velocity());}}class b2SolverData{constructor(){this.step=new b2TimeStep();}}let g_blockSolve=false;class b2VelocityConstraintPoint{constructor(){this.rA=new b2Vec2();this.rB=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.normalMass=0;this.tangentMass=0;this.velocityBias=0;}static MakeArray(length){return b2MakeArray(length,i=>new b2VelocityConstraintPoint());}}class b2ContactVelocityConstraint{constructor(){this.points=b2VelocityConstraintPoint.MakeArray(b2_maxManifoldPoints);this.normal=new b2Vec2();this.tangent=new b2Vec2();this.normalMass=new b2Mat22();this.K=new b2Mat22();this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.invIA=0;this.invIB=0;this.friction=0;this.restitution=0;this.tangentSpeed=0;this.pointCount=0;this.contactIndex=0;}static MakeArray(length){return b2MakeArray(length,i=>new b2ContactVelocityConstraint());}}class b2ContactPositionConstraint{constructor(){this.localPoints=b2Vec2.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2();this.localPoint=new b2Vec2();this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.localCenterA=new b2Vec2();this.localCenterB=new b2Vec2();this.invIA=0;this.invIB=0;this.type=exports.b2ManifoldType.e_unknown;this.radiusA=0;this.radiusB=0;this.pointCount=0;}static MakeArray(length){return b2MakeArray(length,i=>new b2ContactPositionConstraint());}}class b2ContactSolverDef{constructor(){this.step=new b2TimeStep();this.count=0;}}class b2PositionSolverManifold{constructor(){this.normal=new b2Vec2();this.point=new b2Vec2();this.separation=0;}Initialize(pc,xfA,xfB,index){const pointA=b2PositionSolverManifold.Initialize_s_pointA;const pointB=b2PositionSolverManifold.Initialize_s_pointB;const planePoint=b2PositionSolverManifold.Initialize_s_planePoint;const clipPoint=b2PositionSolverManifold.Initialize_s_clipPoint;switch(pc.type){case exports.b2ManifoldType.e_circles:{b2Transform.MulXV(xfA,pc.localPoint,pointA);b2Transform.MulXV(xfB,pc.localPoints[0],pointB);b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize();b2Vec2.MidVV(pointA,pointB,this.point);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;break;}case exports.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,pc.localNormal,this.normal);b2Transform.MulXV(xfA,pc.localPoint,planePoint);b2Transform.MulXV(xfB,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);break;}case exports.b2ManifoldType.e_faceB:{b2Rot.MulRV(xfB.q,pc.localNormal,this.normal);b2Transform.MulXV(xfB,pc.localPoint,planePoint);b2Transform.MulXV(xfA,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);this.normal.SelfNeg();break;}}}}b2PositionSolverManifold.Initialize_s_pointA=new b2Vec2();b2PositionSolverManifold.Initialize_s_pointB=new b2Vec2();b2PositionSolverManifold.Initialize_s_planePoint=new b2Vec2();b2PositionSolverManifold.Initialize_s_clipPoint=new b2Vec2();class b2ContactSolver{constructor(){this.m_step=new b2TimeStep();this.m_positionConstraints=b2ContactPositionConstraint.MakeArray(1024);this.m_velocityConstraints=b2ContactVelocityConstraint.MakeArray(1024);this.m_count=0;}Initialize(def){this.m_step.Copy(def.step);this.m_count=def.count;if(this.m_positionConstraints.length<this.m_count){const new_length=b2Max(this.m_positionConstraints.length*2,this.m_count);while(this.m_positionConstraints.length<new_length){this.m_positionConstraints[this.m_positionConstraints.length]=new b2ContactPositionConstraint();}}if(this.m_velocityConstraints.length<this.m_count){const new_length=b2Max(this.m_velocityConstraints.length*2,this.m_count);while(this.m_velocityConstraints.length<new_length){this.m_velocityConstraints[this.m_velocityConstraints.length]=new b2ContactVelocityConstraint();}}this.m_positions=def.positions;this.m_velocities=def.velocities;this.m_contacts=def.contacts;for(let i=0;i<this.m_count;++i){const contact=this.m_contacts[i];const fixtureA=contact.m_fixtureA;const fixtureB=contact.m_fixtureB;const shapeA=fixtureA.GetShape();const shapeB=fixtureB.GetShape();const radiusA=shapeA.m_radius;const radiusB=shapeB.m_radius;const bodyA=fixtureA.GetBody();const bodyB=fixtureB.GetBody();const manifold=contact.GetManifold();const pointCount=manifold.pointCount;const vc=this.m_velocityConstraints[i];vc.friction=contact.m_friction;vc.restitution=contact.m_restitution;vc.tangentSpeed=contact.m_tangentSpeed;vc.indexA=bodyA.m_islandIndex;vc.indexB=bodyB.m_islandIndex;vc.invMassA=bodyA.m_invMass;vc.invMassB=bodyB.m_invMass;vc.invIA=bodyA.m_invI;vc.invIB=bodyB.m_invI;vc.contactIndex=i;vc.pointCount=pointCount;vc.K.SetZero();vc.normalMass.SetZero();const pc=this.m_positionConstraints[i];pc.indexA=bodyA.m_islandIndex;pc.indexB=bodyB.m_islandIndex;pc.invMassA=bodyA.m_invMass;pc.invMassB=bodyB.m_invMass;pc.localCenterA.Copy(bodyA.m_sweep.localCenter);pc.localCenterB.Copy(bodyB.m_sweep.localCenter);pc.invIA=bodyA.m_invI;pc.invIB=bodyB.m_invI;pc.localNormal.Copy(manifold.localNormal);pc.localPoint.Copy(manifold.localPoint);pc.pointCount=pointCount;pc.radiusA=radiusA;pc.radiusB=radiusB;pc.type=manifold.type;for(let j=0;j<pointCount;++j){const cp=manifold.points[j];const vcp=vc.points[j];if(this.m_step.warmStarting){vcp.normalImpulse=this.m_step.dtRatio*cp.normalImpulse;vcp.tangentImpulse=this.m_step.dtRatio*cp.tangentImpulse;}else {vcp.normalImpulse=0;vcp.tangentImpulse=0;}vcp.rA.SetZero();vcp.rB.SetZero();vcp.normalMass=0;vcp.tangentMass=0;vcp.velocityBias=0;pc.localPoints[j].Copy(cp.localPoint);}}return this;}InitializeVelocityConstraints(){const xfA=b2ContactSolver.InitializeVelocityConstraints_s_xfA;const xfB=b2ContactSolver.InitializeVelocityConstraints_s_xfB;const worldManifold=b2ContactSolver.InitializeVelocityConstraints_s_worldManifold;const k_maxConditionNumber=1000;for(let i=0;i<this.m_count;++i){const vc=this.m_velocityConstraints[i];const pc=this.m_positionConstraints[i];const radiusA=pc.radiusA;const radiusB=pc.radiusB;const manifold=this.m_contacts[vc.contactIndex].GetManifold();const indexA=vc.indexA;const indexB=vc.indexB;const mA=vc.invMassA;const mB=vc.invMassB;const iA=vc.invIA;const iB=vc.invIB;const localCenterA=pc.localCenterA;const localCenterB=pc.localCenterB;const cA=this.m_positions[indexA].c;const aA=this.m_positions[indexA].a;const vA=this.m_velocities[indexA].v;const wA=this.m_velocities[indexA].w;const cB=this.m_positions[indexB].c;const aB=this.m_positions[indexB].a;const vB=this.m_velocities[indexB].v;const wB=this.m_velocities[indexB].w;xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);worldManifold.Initialize(manifold,xfA,radiusA,xfB,radiusB);vc.normal.Copy(worldManifold.normal);b2Vec2.CrossVOne(vc.normal,vc.tangent);const pointCount=vc.pointCount;for(let j=0;j<pointCount;++j){const vcp=vc.points[j];b2Vec2.SubVV(worldManifold.points[j],cA,vcp.rA);b2Vec2.SubVV(worldManifold.points[j],cB,vcp.rB);const rnA=b2Vec2.CrossVV(vcp.rA,vc.normal);const rnB=b2Vec2.CrossVV(vcp.rB,vc.normal);const kNormal=mA+mB+iA*rnA*rnA+iB*rnB*rnB;vcp.normalMass=kNormal>0?1/kNormal:0;const tangent=vc.tangent;const rtA=b2Vec2.CrossVV(vcp.rA,tangent);const rtB=b2Vec2.CrossVV(vcp.rB,tangent);const kTangent=mA+mB+iA*rtA*rtA+iB*rtB*rtB;vcp.tangentMass=kTangent>0?1/kTangent:0;vcp.velocityBias=0;const vRel=b2Vec2.DotVV(vc.normal,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),b2Vec2.s_t0));if(vRel<-b2_velocityThreshold){vcp.velocityBias+=-vc.restitution*vRel;}}if(vc.pointCount===2&&g_blockSolve){const vcp1=vc.points[0];const vcp2=vc.points[1];const rn1A=b2Vec2.CrossVV(vcp1.rA,vc.normal);const rn1B=b2Vec2.CrossVV(vcp1.rB,vc.normal);const rn2A=b2Vec2.CrossVV(vcp2.rA,vc.normal);const rn2B=b2Vec2.CrossVV(vcp2.rB,vc.normal);const k11=mA+mB+iA*rn1A*rn1A+iB*rn1B*rn1B;const k22=mA+mB+iA*rn2A*rn2A+iB*rn2B*rn2B;const k12=mA+mB+iA*rn1A*rn2A+iB*rn1B*rn2B;if(k11*k11<k_maxConditionNumber*(k11*k22-k12*k12)){vc.K.ex.Set(k11,k12);vc.K.ey.Set(k12,k22);vc.K.GetInverse(vc.normalMass);}else {vc.pointCount=1;}}}}WarmStart(){const P=b2ContactSolver.WarmStart_s_P;for(let i=0;i<this.m_count;++i){const vc=this.m_velocityConstraints[i];const indexA=vc.indexA;const indexB=vc.indexB;const mA=vc.invMassA;const iA=vc.invIA;const mB=vc.invMassB;const iB=vc.invIB;const pointCount=vc.pointCount;const vA=this.m_velocities[indexA].v;let wA=this.m_velocities[indexA].w;const vB=this.m_velocities[indexB].v;let wB=this.m_velocities[indexB].w;const normal=vc.normal;const tangent=vc.tangent;for(let j=0;j<pointCount;++j){const vcp=vc.points[j];b2Vec2.AddVV(b2Vec2.MulSV(vcp.normalImpulse,normal,b2Vec2.s_t0),b2Vec2.MulSV(vcp.tangentImpulse,tangent,b2Vec2.s_t1),P);wA-=iA*b2Vec2.CrossVV(vcp.rA,P);vA.SelfMulSub(mA,P);wB+=iB*b2Vec2.CrossVV(vcp.rB,P);vB.SelfMulAdd(mB,P);}this.m_velocities[indexA].w=wA;this.m_velocities[indexB].w=wB;}}SolveVelocityConstraints(){const dv=b2ContactSolver.SolveVelocityConstraints_s_dv;const dv1=b2ContactSolver.SolveVelocityConstraints_s_dv1;const dv2=b2ContactSolver.SolveVelocityConstraints_s_dv2;const P=b2ContactSolver.SolveVelocityConstraints_s_P;const a=b2ContactSolver.SolveVelocityConstraints_s_a;const b=b2ContactSolver.SolveVelocityConstraints_s_b;const x=b2ContactSolver.SolveVelocityConstraints_s_x;const d=b2ContactSolver.SolveVelocityConstraints_s_d;const P1=b2ContactSolver.SolveVelocityConstraints_s_P1;const P2=b2ContactSolver.SolveVelocityConstraints_s_P2;const P1P2=b2ContactSolver.SolveVelocityConstraints_s_P1P2;for(let i=0;i<this.m_count;++i){const vc=this.m_velocityConstraints[i];const indexA=vc.indexA;const indexB=vc.indexB;const mA=vc.invMassA;const iA=vc.invIA;const mB=vc.invMassB;const iB=vc.invIB;const pointCount=vc.pointCount;const vA=this.m_velocities[indexA].v;let wA=this.m_velocities[indexA].w;const vB=this.m_velocities[indexB].v;let wB=this.m_velocities[indexB].w;const normal=vc.normal;const tangent=vc.tangent;const friction=vc.friction;for(let j=0;j<pointCount;++j){const vcp=vc.points[j];b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),dv);const vt=b2Vec2.DotVV(dv,tangent)-vc.tangentSpeed;let lambda=vcp.tangentMass*-vt;const maxFriction=friction*vcp.normalImpulse;const newImpulse=b2Clamp(vcp.tangentImpulse+lambda,-maxFriction,maxFriction);lambda=newImpulse-vcp.tangentImpulse;vcp.tangentImpulse=newImpulse;b2Vec2.MulSV(lambda,tangent,P);vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(vcp.rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(vcp.rB,P);}if(vc.pointCount===1||g_blockSolve===false){for(let j=0;j<pointCount;++j){const vcp=vc.points[j];b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),dv);const vn=b2Vec2.DotVV(dv,normal);let lambda=-vcp.normalMass*(vn-vcp.velocityBias);const newImpulse=b2Max(vcp.normalImpulse+lambda,0);lambda=newImpulse-vcp.normalImpulse;vcp.normalImpulse=newImpulse;b2Vec2.MulSV(lambda,normal,P);vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(vcp.rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(vcp.rB,P);}}else {const cp1=vc.points[0];const cp2=vc.points[1];a.Set(cp1.normalImpulse,cp2.normalImpulse);b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,cp1.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,cp1.rA,b2Vec2.s_t1),dv1);b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,cp2.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,cp2.rA,b2Vec2.s_t1),dv2);let vn1=b2Vec2.DotVV(dv1,normal);let vn2=b2Vec2.DotVV(dv2,normal);b.x=vn1-cp1.velocityBias;b.y=vn2-cp2.velocityBias;b.SelfSub(b2Mat22.MulMV(vc.K,a,b2Vec2.s_t0));for(;;){b2Mat22.MulMV(vc.normalMass,b,x).SelfNeg();if(x.x>=0&&x.y>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=-cp1.normalMass*b.x;x.y=0;vn1=0;vn2=vc.K.ex.y*x.x+b.y;if(x.x>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=0;x.y=-cp2.normalMass*b.y;vn1=vc.K.ey.x*x.y+b.x;vn2=0;if(x.y>=0&&vn1>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=0;x.y=0;vn1=b.x;vn2=b.y;if(vn1>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}break;}}this.m_velocities[indexA].w=wA;this.m_velocities[indexB].w=wB;}}StoreImpulses(){for(let i=0;i<this.m_count;++i){const vc=this.m_velocityConstraints[i];const manifold=this.m_contacts[vc.contactIndex].GetManifold();for(let j=0;j<vc.pointCount;++j){manifold.points[j].normalImpulse=vc.points[j].normalImpulse;manifold.points[j].tangentImpulse=vc.points[j].tangentImpulse;}}}SolvePositionConstraints(){const xfA=b2ContactSolver.SolvePositionConstraints_s_xfA;const xfB=b2ContactSolver.SolvePositionConstraints_s_xfB;const psm=b2ContactSolver.SolvePositionConstraints_s_psm;const rA=b2ContactSolver.SolvePositionConstraints_s_rA;const rB=b2ContactSolver.SolvePositionConstraints_s_rB;const P=b2ContactSolver.SolvePositionConstraints_s_P;let minSeparation=0;for(let i=0;i<this.m_count;++i){const pc=this.m_positionConstraints[i];const indexA=pc.indexA;const indexB=pc.indexB;const localCenterA=pc.localCenterA;const mA=pc.invMassA;const iA=pc.invIA;const localCenterB=pc.localCenterB;const mB=pc.invMassB;const iB=pc.invIB;const pointCount=pc.pointCount;const cA=this.m_positions[indexA].c;let aA=this.m_positions[indexA].a;const cB=this.m_positions[indexB].c;let aB=this.m_positions[indexB].a;for(let j=0;j<pointCount;++j){xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);psm.Initialize(pc,xfA,xfB,j);const normal=psm.normal;const point=psm.point;const separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);const C=b2Clamp(b2_baumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);const rnA=b2Vec2.CrossVV(rA,normal);const rnB=b2Vec2.CrossVV(rB,normal);const K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;const impulse=K>0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB;}return minSeparation>-3*b2_linearSlop;}SolveTOIPositionConstraints(toiIndexA,toiIndexB){const xfA=b2ContactSolver.SolveTOIPositionConstraints_s_xfA;const xfB=b2ContactSolver.SolveTOIPositionConstraints_s_xfB;const psm=b2ContactSolver.SolveTOIPositionConstraints_s_psm;const rA=b2ContactSolver.SolveTOIPositionConstraints_s_rA;const rB=b2ContactSolver.SolveTOIPositionConstraints_s_rB;const P=b2ContactSolver.SolveTOIPositionConstraints_s_P;let minSeparation=0;for(let i=0;i<this.m_count;++i){const pc=this.m_positionConstraints[i];const indexA=pc.indexA;const indexB=pc.indexB;const localCenterA=pc.localCenterA;const localCenterB=pc.localCenterB;const pointCount=pc.pointCount;let mA=0;let iA=0;if(indexA===toiIndexA||indexA===toiIndexB){mA=pc.invMassA;iA=pc.invIA;}let mB=0;let iB=0;if(indexB===toiIndexA||indexB===toiIndexB){mB=pc.invMassB;iB=pc.invIB;}const cA=this.m_positions[indexA].c;let aA=this.m_positions[indexA].a;const cB=this.m_positions[indexB].c;let aB=this.m_positions[indexB].a;for(let j=0;j<pointCount;++j){xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);psm.Initialize(pc,xfA,xfB,j);const normal=psm.normal;const point=psm.point;const separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);const C=b2Clamp(b2_toiBaumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);const rnA=b2Vec2.CrossVV(rA,normal);const rnB=b2Vec2.CrossVV(rB,normal);const K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;const impulse=K>0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB;}return minSeparation>=-1.5*b2_linearSlop;}}b2ContactSolver.InitializeVelocityConstraints_s_xfA=new b2Transform();b2ContactSolver.InitializeVelocityConstraints_s_xfB=new b2Transform();b2ContactSolver.InitializeVelocityConstraints_s_worldManifold=new b2WorldManifold();b2ContactSolver.WarmStart_s_P=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv1=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv2=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_a=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_b=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_x=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_d=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P1=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P2=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P1P2=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_xfA=new b2Transform();b2ContactSolver.SolvePositionConstraints_s_xfB=new b2Transform();b2ContactSolver.SolvePositionConstraints_s_psm=new b2PositionSolverManifold();b2ContactSolver.SolvePositionConstraints_s_rA=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_rB=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_P=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_xfA=new b2Transform();b2ContactSolver.SolveTOIPositionConstraints_s_xfB=new b2Transform();b2ContactSolver.SolveTOIPositionConstraints_s_psm=new b2PositionSolverManifold();b2ContactSolver.SolveTOIPositionConstraints_s_rA=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_rB=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_P=new b2Vec2();class b2Island{constructor(){this.m_bodies=[];this.m_contacts=[];this.m_joints=[];this.m_positions=b2Position.MakeArray(1024);this.m_velocities=b2Velocity.MakeArray(1024);this.m_bodyCount=0;this.m_jointCount=0;this.m_contactCount=0;this.m_bodyCapacity=0;this.m_contactCapacity=0;this.m_jointCapacity=0;}Initialize(bodyCapacity,contactCapacity,jointCapacity,listener){this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_listener=listener;if(this.m_positions.length<bodyCapacity){const new_length=b2Max(this.m_positions.length*2,bodyCapacity);while(this.m_positions.length<new_length){this.m_positions[this.m_positions.length]=new b2Position();}}if(this.m_velocities.length<bodyCapacity){const new_length=b2Max(this.m_velocities.length*2,bodyCapacity);while(this.m_velocities.length<new_length){this.m_velocities[this.m_velocities.length]=new b2Velocity();}}}Clear(){this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;}AddBody(body){body.m_islandIndex=this.m_bodyCount;this.m_bodies[this.m_bodyCount++]=body;}AddContact(contact){this.m_contacts[this.m_contactCount++]=contact;}AddJoint(joint){this.m_joints[this.m_jointCount++]=joint;}Solve(profile,step,gravity,allowSleep){const timer=b2Island.s_timer.Reset();const h=step.dt;for(let i=0;i<this.m_bodyCount;++i){const b=this.m_bodies[i];this.m_positions[i].c.Copy(b.m_sweep.c);const a=b.m_sweep.a;const v=this.m_velocities[i].v.Copy(b.m_linearVelocity);let w=b.m_angularVelocity;b.m_sweep.c0.Copy(b.m_sweep.c);b.m_sweep.a0=b.m_sweep.a;if(b.m_type===exports.b2BodyType.b2_dynamicBody){v.x+=h*(b.m_gravityScale*gravity.x+b.m_invMass*b.m_force.x);v.y+=h*(b.m_gravityScale*gravity.y+b.m_invMass*b.m_force.y);w+=h*b.m_invI*b.m_torque;v.SelfMul(1.0/(1.0+h*b.m_linearDamping));w*=1.0/(1.0+h*b.m_angularDamping);}this.m_positions[i].a=a;this.m_velocities[i].w=w;}timer.Reset();const solverData=b2Island.s_solverData;solverData.step.Copy(step);solverData.positions=this.m_positions;solverData.velocities=this.m_velocities;const contactSolverDef=b2Island.s_contactSolverDef;contactSolverDef.step.Copy(step);contactSolverDef.contacts=this.m_contacts;contactSolverDef.count=this.m_contactCount;contactSolverDef.positions=this.m_positions;contactSolverDef.velocities=this.m_velocities;const contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);contactSolver.InitializeVelocityConstraints();if(step.warmStarting){contactSolver.WarmStart();}for(let i=0;i<this.m_jointCount;++i){this.m_joints[i].InitVelocityConstraints(solverData);}profile.solveInit=timer.GetMilliseconds();timer.Reset();for(let i=0;i<step.velocityIterations;++i){for(let j=0;j<this.m_jointCount;++j){this.m_joints[j].SolveVelocityConstraints(solverData);}contactSolver.SolveVelocityConstraints();}contactSolver.StoreImpulses();profile.solveVelocity=timer.GetMilliseconds();for(let i=0;i<this.m_bodyCount;++i){const c=this.m_positions[i].c;let a=this.m_positions[i].a;const v=this.m_velocities[i].v;let w=this.m_velocities[i].w;const translation=b2Vec2.MulSV(h,v,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){const ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio);}const rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){const ratio=b2_maxRotation/b2Abs(rotation);w*=ratio;}c.x+=h*v.x;c.y+=h*v.y;a+=h*w;this.m_positions[i].a=a;this.m_velocities[i].w=w;}timer.Reset();let positionSolved=false;for(let i=0;i<step.positionIterations;++i){const contactsOkay=contactSolver.SolvePositionConstraints();let jointsOkay=true;for(let j=0;j<this.m_jointCount;++j){const jointOkay=this.m_joints[j].SolvePositionConstraints(solverData);jointsOkay=jointsOkay&&jointOkay;}if(contactsOkay&&jointsOkay){positionSolved=true;break;}}for(let i=0;i<this.m_bodyCount;++i){const body=this.m_bodies[i];body.m_sweep.c.Copy(this.m_positions[i].c);body.m_sweep.a=this.m_positions[i].a;body.m_linearVelocity.Copy(this.m_velocities[i].v);body.m_angularVelocity=this.m_velocities[i].w;body.SynchronizeTransform();}profile.solvePosition=timer.GetMilliseconds();this.Report(contactSolver.m_velocityConstraints);if(allowSleep){let minSleepTime=b2_maxFloat;const linTolSqr=b2_linearSleepTolerance*b2_linearSleepTolerance;const angTolSqr=b2_angularSleepTolerance*b2_angularSleepTolerance;for(let i=0;i<this.m_bodyCount;++i){const b=this.m_bodies[i];if(b.GetType()===exports.b2BodyType.b2_staticBody){continue;}if(!b.m_autoSleepFlag||b.m_angularVelocity*b.m_angularVelocity>angTolSqr||b2Vec2.DotVV(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr){b.m_sleepTime=0;minSleepTime=0;}else {b.m_sleepTime+=h;minSleepTime=b2Min(minSleepTime,b.m_sleepTime);}}if(minSleepTime>=b2_timeToSleep&&positionSolved){for(let i=0;i<this.m_bodyCount;++i){const b=this.m_bodies[i];b.SetAwake(false);}}}}SolveTOI(subStep,toiIndexA,toiIndexB){for(let i=0;i<this.m_bodyCount;++i){const b=this.m_bodies[i];this.m_positions[i].c.Copy(b.m_sweep.c);this.m_positions[i].a=b.m_sweep.a;this.m_velocities[i].v.Copy(b.m_linearVelocity);this.m_velocities[i].w=b.m_angularVelocity;}const contactSolverDef=b2Island.s_contactSolverDef;contactSolverDef.contacts=this.m_contacts;contactSolverDef.count=this.m_contactCount;contactSolverDef.step.Copy(subStep);contactSolverDef.positions=this.m_positions;contactSolverDef.velocities=this.m_velocities;const contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);for(let i=0;i<subStep.positionIterations;++i){const contactsOkay=contactSolver.SolveTOIPositionConstraints(toiIndexA,toiIndexB);if(contactsOkay){break;}}this.m_bodies[toiIndexA].m_sweep.c0.Copy(this.m_positions[toiIndexA].c);this.m_bodies[toiIndexA].m_sweep.a0=this.m_positions[toiIndexA].a;this.m_bodies[toiIndexB].m_sweep.c0.Copy(this.m_positions[toiIndexB].c);this.m_bodies[toiIndexB].m_sweep.a0=this.m_positions[toiIndexB].a;contactSolver.InitializeVelocityConstraints();for(let i=0;i<subStep.velocityIterations;++i){contactSolver.SolveVelocityConstraints();}const h=subStep.dt;for(let i=0;i<this.m_bodyCount;++i){const c=this.m_positions[i].c;let a=this.m_positions[i].a;const v=this.m_velocities[i].v;let w=this.m_velocities[i].w;const translation=b2Vec2.MulSV(h,v,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){const ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio);}const rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){const ratio=b2_maxRotation/b2Abs(rotation);w*=ratio;}c.SelfMulAdd(h,v);a+=h*w;this.m_positions[i].a=a;this.m_velocities[i].w=w;const body=this.m_bodies[i];body.m_sweep.c.Copy(c);body.m_sweep.a=a;body.m_linearVelocity.Copy(v);body.m_angularVelocity=w;body.SynchronizeTransform();}this.Report(contactSolver.m_velocityConstraints);}Report(constraints){if(this.m_listener===null){return;}for(let i=0;i<this.m_contactCount;++i){const c=this.m_contacts[i];if(!c){continue;}const vc=constraints[i];const impulse=b2Island.s_impulse;impulse.count=vc.pointCount;for(let j=0;j<vc.pointCount;++j){impulse.normalImpulses[j]=vc.points[j].normalImpulse;impulse.tangentImpulses[j]=vc.points[j].tangentImpulse;}this.m_listener.PostSolve(c,impulse);}}}b2Island.s_timer=new b2Timer();b2Island.s_solverData=new b2SolverData();b2Island.s_contactSolverDef=new b2ContactSolverDef();b2Island.s_contactSolver=new b2ContactSolver();b2Island.s_translation=new b2Vec2();b2Island.s_impulse=new b2ContactImpulse();(function(b2ParticleFlag){b2ParticleFlag[b2ParticleFlag["b2_waterParticle"]=0]="b2_waterParticle";b2ParticleFlag[b2ParticleFlag["b2_zombieParticle"]=2]="b2_zombieParticle";b2ParticleFlag[b2ParticleFlag["b2_wallParticle"]=4]="b2_wallParticle";b2ParticleFlag[b2ParticleFlag["b2_springParticle"]=8]="b2_springParticle";b2ParticleFlag[b2ParticleFlag["b2_elasticParticle"]=16]="b2_elasticParticle";b2ParticleFlag[b2ParticleFlag["b2_viscousParticle"]=32]="b2_viscousParticle";b2ParticleFlag[b2ParticleFlag["b2_powderParticle"]=64]="b2_powderParticle";b2ParticleFlag[b2ParticleFlag["b2_tensileParticle"]=128]="b2_tensileParticle";b2ParticleFlag[b2ParticleFlag["b2_colorMixingParticle"]=256]="b2_colorMixingParticle";b2ParticleFlag[b2ParticleFlag["b2_destructionListenerParticle"]=512]="b2_destructionListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_barrierParticle"]=1024]="b2_barrierParticle";b2ParticleFlag[b2ParticleFlag["b2_staticPressureParticle"]=2048]="b2_staticPressureParticle";b2ParticleFlag[b2ParticleFlag["b2_reactiveParticle"]=4096]="b2_reactiveParticle";b2ParticleFlag[b2ParticleFlag["b2_repulsiveParticle"]=8192]="b2_repulsiveParticle";b2ParticleFlag[b2ParticleFlag["b2_fixtureContactListenerParticle"]=16384]="b2_fixtureContactListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_particleContactListenerParticle"]=32768]="b2_particleContactListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_fixtureContactFilterParticle"]=65536]="b2_fixtureContactFilterParticle";b2ParticleFlag[b2ParticleFlag["b2_particleContactFilterParticle"]=131072]="b2_particleContactFilterParticle";})(exports.b2ParticleFlag||(exports.b2ParticleFlag={}));class b2ParticleDef{constructor(){this.flags=0;this.position=new b2Vec2();this.velocity=new b2Vec2();this.color=new b2Color(0,0,0,0);this.lifetime=0.0;this.userData=null;this.group=null;}}function b2CalculateParticleIterations(gravity,radius,timeStep){const B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS=8;const B2_RADIUS_THRESHOLD=0.01;const iterations=Math.ceil(Math.sqrt(gravity/(B2_RADIUS_THRESHOLD*radius))*timeStep);return b2Clamp(iterations,1,B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS);}class b2ParticleHandle{constructor(){this.m_index=b2_invalidParticleIndex;}GetIndex(){return this.m_index;}SetIndex(index){this.m_index=index;}}(function(b2ParticleGroupFlag){b2ParticleGroupFlag[b2ParticleGroupFlag["b2_solidParticleGroup"]=1]="b2_solidParticleGroup";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_rigidParticleGroup"]=2]="b2_rigidParticleGroup";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupCanBeEmpty"]=4]="b2_particleGroupCanBeEmpty";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupWillBeDestroyed"]=8]="b2_particleGroupWillBeDestroyed";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupNeedsUpdateDepth"]=16]="b2_particleGroupNeedsUpdateDepth";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupInternalMask"]=24]="b2_particleGroupInternalMask";})(exports.b2ParticleGroupFlag||(exports.b2ParticleGroupFlag={}));class b2ParticleGroupDef{constructor(){this.flags=0;this.groupFlags=0;this.position=new b2Vec2();this.angle=0.0;this.linearVelocity=new b2Vec2();this.angularVelocity=0.0;this.color=new b2Color();this.strength=1.0;this.shapeCount=0;this.stride=0;this.particleCount=0;this.lifetime=0;this.userData=null;this.group=null;}}class b2ParticleGroup{constructor(system){this.m_firstIndex=0;this.m_lastIndex=0;this.m_groupFlags=0;this.m_strength=1.0;this.m_prev=null;this.m_next=null;this.m_timestamp=-1;this.m_mass=0.0;this.m_inertia=0.0;this.m_center=new b2Vec2();this.m_linearVelocity=new b2Vec2();this.m_angularVelocity=0.0;this.m_transform=new b2Transform();this.m_userData=null;this.m_system=system;}GetNext(){return this.m_next;}GetParticleSystem(){return this.m_system;}GetParticleCount(){return this.m_lastIndex-this.m_firstIndex;}GetBufferIndex(){return this.m_firstIndex;}ContainsParticle(index){return this.m_firstIndex<=index&&index<this.m_lastIndex;}GetAllParticleFlags(){if(!this.m_system.m_flagsBuffer.data){throw new Error();}let flags=0;for(let i=this.m_firstIndex;i<this.m_lastIndex;i++){flags|=this.m_system.m_flagsBuffer.data[i];}return flags;}GetGroupFlags(){return this.m_groupFlags;}SetGroupFlags(flags){flags|=this.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupInternalMask;this.m_system.SetGroupFlags(this,flags);}GetMass(){this.UpdateStatistics();return this.m_mass;}GetInertia(){this.UpdateStatistics();return this.m_inertia;}GetCenter(){this.UpdateStatistics();return this.m_center;}GetLinearVelocity(){this.UpdateStatistics();return this.m_linearVelocity;}GetAngularVelocity(){this.UpdateStatistics();return this.m_angularVelocity;}GetTransform(){return this.m_transform;}GetPosition(){return this.m_transform.p;}GetAngle(){return this.m_transform.q.GetAngle();}GetLinearVelocityFromWorldPoint(worldPoint,out){const s_t0=b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0;this.UpdateStatistics();return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_center,s_t0),out);}GetUserData(){return this.m_userData;}SetUserData(data){this.m_userData=data;}ApplyForce(force){this.m_system.ApplyForce(this.m_firstIndex,this.m_lastIndex,force);}ApplyLinearImpulse(impulse){this.m_system.ApplyLinearImpulse(this.m_firstIndex,this.m_lastIndex,impulse);}DestroyParticles(callDestructionListener){if(this.m_system.m_world.IsLocked()){throw new Error();}for(let i=this.m_firstIndex;i<this.m_lastIndex;i++){this.m_system.DestroyParticle(i,callDestructionListener);}}UpdateStatistics(){if(!this.m_system.m_positionBuffer.data){throw new Error();}if(!this.m_system.m_velocityBuffer.data){throw new Error();}const p=new b2Vec2();const v=new b2Vec2();if(this.m_timestamp!==this.m_system.m_timestamp){const m=this.m_system.GetParticleMass();this.m_mass=m*(this.m_lastIndex-this.m_firstIndex);this.m_center.SetZero();this.m_linearVelocity.SetZero();for(let i=this.m_firstIndex;i<this.m_lastIndex;i++){this.m_center.SelfMulAdd(m,this.m_system.m_positionBuffer.data[i]);this.m_linearVelocity.SelfMulAdd(m,this.m_system.m_velocityBuffer.data[i]);}if(this.m_mass>0){const inv_mass=1/this.m_mass;this.m_center.SelfMul(inv_mass);this.m_linearVelocity.SelfMul(inv_mass);}this.m_inertia=0;this.m_angularVelocity=0;for(let i=this.m_firstIndex;i<this.m_lastIndex;i++){b2Vec2.SubVV(this.m_system.m_positionBuffer.data[i],this.m_center,p);b2Vec2.SubVV(this.m_system.m_velocityBuffer.data[i],this.m_linearVelocity,v);this.m_inertia+=m*b2Vec2.DotVV(p,p);this.m_angularVelocity+=m*b2Vec2.CrossVV(p,v);}if(this.m_inertia>0){this.m_angularVelocity*=1/this.m_inertia;}this.m_timestamp=this.m_system.m_timestamp;}}}b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0=new b2Vec2();class b2StackQueue{constructor(capacity){this.m_buffer=[];this.m_front=0;this.m_back=0;this.m_buffer.fill(null,0,capacity);}get m_capacity(){return this.m_buffer.length;}Push(item){if(this.m_back>=this.m_capacity){for(let i=this.m_front;i<this.m_back;i++){this.m_buffer[i-this.m_front]=this.m_buffer[i];}this.m_back-=this.m_front;this.m_front=0;}this.m_buffer[this.m_back]=item;this.m_back++;}Pop(){this.m_buffer[this.m_front]=null;this.m_front++;}Empty(){return this.m_front===this.m_back;}Front(){const item=this.m_buffer[this.m_front];if(!item){throw new Error();}return item;}}class b2VoronoiDiagram{constructor(generatorCapacity){this.m_generatorCapacity=0;this.m_generatorCount=0;this.m_countX=0;this.m_countY=0;this.m_diagram=[];this.m_generatorBuffer=b2MakeArray(generatorCapacity,index=>new b2VoronoiDiagram_Generator());this.m_generatorCapacity=generatorCapacity;}AddGenerator(center,tag,necessary){const g=this.m_generatorBuffer[this.m_generatorCount++];g.center.Copy(center);g.tag=tag;g.necessary=necessary;}Generate(radius,margin){const inverseRadius=1/radius;const lower=new b2Vec2(+b2_maxFloat,+b2_maxFloat);const upper=new b2Vec2(-b2_maxFloat,-b2_maxFloat);let necessary_count=0;for(let k=0;k<this.m_generatorCount;k++){const g=this.m_generatorBuffer[k];if(g.necessary){b2Vec2.MinV(lower,g.center,lower);b2Vec2.MaxV(upper,g.center,upper);++necessary_count;}}if(necessary_count===0){this.m_countX=0;this.m_countY=0;return;}lower.x-=margin;lower.y-=margin;upper.x+=margin;upper.y+=margin;this.m_countX=1+Math.floor(inverseRadius*(upper.x-lower.x));this.m_countY=1+Math.floor(inverseRadius*(upper.y-lower.y));this.m_diagram=[];const queue=new b2StackQueue(4*this.m_countX*this.m_countY);for(let k=0;k<this.m_generatorCount;k++){const g=this.m_generatorBuffer[k];g.center.SelfSub(lower).SelfMul(inverseRadius);const x=Math.floor(g.center.x);const y=Math.floor(g.center.y);if(x>=0&&y>=0&&x<this.m_countX&&y<this.m_countY){queue.Push(new b2VoronoiDiagram_Task(x,y,x+y*this.m_countX,g));}}while(!queue.Empty()){const task=queue.Front();const x=task.m_x;const y=task.m_y;const i=task.m_i;const g=task.m_generator;queue.Pop();if(!this.m_diagram[i]){this.m_diagram[i]=g;if(x>0){queue.Push(new b2VoronoiDiagram_Task(x-1,y,i-1,g));}if(y>0){queue.Push(new b2VoronoiDiagram_Task(x,y-1,i-this.m_countX,g));}if(x<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(x+1,y,i+1,g));}if(y<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(x,y+1,i+this.m_countX,g));}}}for(let y=0;y<this.m_countY;y++){for(let x=0;x<this.m_countX-1;x++){const i=x+y*this.m_countX;const a=this.m_diagram[i];const b=this.m_diagram[i+1];if(a!==b){queue.Push(new b2VoronoiDiagram_Task(x,y,i,b));queue.Push(new b2VoronoiDiagram_Task(x+1,y,i+1,a));}}}for(let y=0;y<this.m_countY-1;y++){for(let x=0;x<this.m_countX;x++){const i=x+y*this.m_countX;const a=this.m_diagram[i];const b=this.m_diagram[i+this.m_countX];if(a!==b){queue.Push(new b2VoronoiDiagram_Task(x,y,i,b));queue.Push(new b2VoronoiDiagram_Task(x,y+1,i+this.m_countX,a));}}}while(!queue.Empty()){const task=queue.Front();const x=task.m_x;const y=task.m_y;const i=task.m_i;const k=task.m_generator;queue.Pop();const a=this.m_diagram[i];const b=k;if(a!==b){const ax=a.center.x-x;const ay=a.center.y-y;const bx=b.center.x-x;const by=b.center.y-y;const a2=ax*ax+ay*ay;const b2=bx*bx+by*by;if(a2>b2){this.m_diagram[i]=b;if(x>0){queue.Push(new b2VoronoiDiagram_Task(x-1,y,i-1,b));}if(y>0){queue.Push(new b2VoronoiDiagram_Task(x,y-1,i-this.m_countX,b));}if(x<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(x+1,y,i+1,b));}if(y<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(x,y+1,i+this.m_countX,b));}}}}}GetNodes(callback){for(let y=0;y<this.m_countY-1;y++){for(let x=0;x<this.m_countX-1;x++){const i=x+y*this.m_countX;const a=this.m_diagram[i];const b=this.m_diagram[i+1];const c=this.m_diagram[i+this.m_countX];const d=this.m_diagram[i+1+this.m_countX];if(b!==c){if(a!==b&&a!==c&&(a.necessary||b.necessary||c.necessary)){callback(a.tag,b.tag,c.tag);}if(d!==b&&d!==c&&(a.necessary||b.necessary||c.necessary)){callback(b.tag,d.tag,c.tag);}}}}}}class b2VoronoiDiagram_Generator{constructor(){this.center=new b2Vec2();this.tag=0;this.necessary=false;}}class b2VoronoiDiagram_Task{constructor(x,y,i,g){this.m_x=x;this.m_y=y;this.m_i=i;this.m_generator=g;}}function std_iter_swap$1(array,a,b){const tmp=array[a];array[a]=array[b];array[b]=tmp;}function default_compare$1(a,b){return a<b;}function std_sort$1(array,first=0,len=array.length-first,cmp=default_compare$1){let left=first;const stack=[];let pos=0;for(;;){for(;left+1<len;len++){const pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(let right=left-1;;){while(cmp(array[++right],pivot)){}while(cmp(pivot,array[--len])){}if(right>=len){break;}std_iter_swap$1(array,right,len);}}if(pos===0){break;}left=len;len=stack[--pos];}return array;}function std_stable_sort(array,first=0,len=array.length-first,cmp=default_compare$1){return std_sort$1(array,first,len,cmp);}function std_remove_if(array,predicate,length=array.length){let l=0;for(let c=0;c<length;++c){if(predicate(array[c])){continue;}if(c===l){++l;continue;}std_iter_swap$1(array,l++,c);}return l;}function std_lower_bound(array,first,last,val,cmp){let count=last-first;while(count>0){const step=Math.floor(count/2);let it=first+step;if(cmp(array[it],val)){first=++it;count-=step+1;}else {count=step;}}return first;}function std_upper_bound(array,first,last,val,cmp){let count=last-first;while(count>0){const step=Math.floor(count/2);let it=first+step;if(!cmp(val,array[it])){first=++it;count-=step+1;}else {count=step;}}return first;}function std_rotate(array,first,n_first,last){let next=n_first;while(first!==next){std_iter_swap$1(array,first++,next++);if(next===last){next=n_first;}else if(first===n_first){n_first=next;}}}function std_unique(array,first,last,cmp){if(first===last){return last;}let result=first;while(++first!==last){if(!cmp(array[result],array[first])){std_iter_swap$1(array,++result,first);}}return ++result;}class b2GrowableBuffer{constructor(allocator){this.data=[];this.count=0;this.capacity=0;this.allocator=allocator;}Append(){if(this.count>=this.capacity){this.Grow();}return this.count++;}Reserve(newCapacity){if(this.capacity>=newCapacity){return;}for(let i=this.capacity;i<newCapacity;++i){this.data[i]=this.allocator();}this.capacity=newCapacity;}Grow(){const newCapacity=this.capacity?2*this.capacity:b2_minParticleSystemBufferCapacity;this.Reserve(newCapacity);}Free(){if(this.data.length===0){return;}this.data=[];this.capacity=0;this.count=0;}Shorten(newEnd){}Data(){return this.data;}GetCount(){return this.count;}SetCount(newCount){this.count=newCount;}GetCapacity(){return this.capacity;}RemoveIf(pred){this.count=std_remove_if(this.data,pred,this.count);}Unique(pred){this.count=std_unique(this.data,0,this.count,pred);}}class b2FixtureParticleQueryCallback extends b2QueryCallback{constructor(system){super();this.m_system=system;}ShouldQueryParticleSystem(system){return false;}ReportFixture(fixture){if(fixture.IsSensor()){return true;}const shape=fixture.GetShape();const childCount=shape.GetChildCount();for(let childIndex=0;childIndex<childCount;childIndex++){const aabb=fixture.GetAABB(childIndex);const enumerator=this.m_system.GetInsideBoundsEnumerator(aabb);let index;while((index=enumerator.GetNext())>=0){this.ReportFixtureAndParticle(fixture,childIndex,index);}}return true;}ReportParticle(system,index){return false;}ReportFixtureAndParticle(fixture,childIndex,index){}}class b2ParticleContact{constructor(){this.indexA=0;this.indexB=0;this.weight=0;this.normal=new b2Vec2();this.flags=0;}SetIndices(a,b){this.indexA=a;this.indexB=b;}SetWeight(w){this.weight=w;}SetNormal(n){this.normal.Copy(n);}SetFlags(f){this.flags=f;}GetIndexA(){return this.indexA;}GetIndexB(){return this.indexB;}GetWeight(){return this.weight;}GetNormal(){return this.normal;}GetFlags(){return this.flags;}IsEqual(rhs){return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&this.weight===rhs.weight&&this.normal.x===rhs.normal.x&&this.normal.y===rhs.normal.y;}IsNotEqual(rhs){return !this.IsEqual(rhs);}ApproximatelyEqual(rhs){const MAX_WEIGHT_DIFF=0.01;const MAX_NORMAL_DIFF_SQ=0.01*0.01;return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&b2Abs(this.weight-rhs.weight)<MAX_WEIGHT_DIFF&&b2Vec2.DistanceSquaredVV(this.normal,rhs.normal)<MAX_NORMAL_DIFF_SQ;}}class b2ParticleBodyContact{constructor(){this.index=0;this.weight=0.0;this.normal=new b2Vec2();this.mass=0.0;}}class b2ParticlePair{constructor(){this.indexA=0;this.indexB=0;this.flags=0;this.strength=0.0;this.distance=0.0;}}class b2ParticleTriad{constructor(){this.indexA=0;this.indexB=0;this.indexC=0;this.flags=0;this.strength=0.0;this.pa=new b2Vec2(0.0,0.0);this.pb=new b2Vec2(0.0,0.0);this.pc=new b2Vec2(0.0,0.0);this.ka=0.0;this.kb=0.0;this.kc=0.0;this.s=0.0;}}class b2ParticleSystemDef{constructor(){this.strictContactCheck=false;this.density=1.0;this.gravityScale=1.0;this.radius=1.0;this.maxCount=0;this.pressureStrength=0.005;this.dampingStrength=1.0;this.elasticStrength=0.25;this.springStrength=0.25;this.viscousStrength=0.25;this.surfaceTensionPressureStrength=0.2;this.surfaceTensionNormalStrength=0.2;this.repulsiveStrength=1.0;this.powderStrength=0.5;this.ejectionStrength=0.5;this.staticPressureStrength=0.2;this.staticPressureRelaxation=0.2;this.staticPressureIterations=8;this.colorMixingStrength=0.5;this.destroyByAge=true;this.lifetimeGranularity=1.0/60.0;}Copy(def){this.strictContactCheck=def.strictContactCheck;this.density=def.density;this.gravityScale=def.gravityScale;this.radius=def.radius;this.maxCount=def.maxCount;this.pressureStrength=def.pressureStrength;this.dampingStrength=def.dampingStrength;this.elasticStrength=def.elasticStrength;this.springStrength=def.springStrength;this.viscousStrength=def.viscousStrength;this.surfaceTensionPressureStrength=def.surfaceTensionPressureStrength;this.surfaceTensionNormalStrength=def.surfaceTensionNormalStrength;this.repulsiveStrength=def.repulsiveStrength;this.powderStrength=def.powderStrength;this.ejectionStrength=def.ejectionStrength;this.staticPressureStrength=def.staticPressureStrength;this.staticPressureRelaxation=def.staticPressureRelaxation;this.staticPressureIterations=def.staticPressureIterations;this.colorMixingStrength=def.colorMixingStrength;this.destroyByAge=def.destroyByAge;this.lifetimeGranularity=def.lifetimeGranularity;return this;}Clone(){return new b2ParticleSystemDef().Copy(this);}}class b2ParticleSystem{constructor(def,world){this.m_paused=false;this.m_timestamp=0;this.m_allParticleFlags=0;this.m_needsUpdateAllParticleFlags=false;this.m_allGroupFlags=0;this.m_needsUpdateAllGroupFlags=false;this.m_hasForce=false;this.m_iterationIndex=0;this.m_inverseDensity=0.0;this.m_particleDiameter=0.0;this.m_inverseDiameter=0.0;this.m_squaredDiameter=0.0;this.m_count=0;this.m_internalAllocatedCapacity=0;this.m_handleIndexBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_flagsBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_positionBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_velocityBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_forceBuffer=[];this.m_weightBuffer=[];this.m_staticPressureBuffer=[];this.m_accumulationBuffer=[];this.m_accumulation2Buffer=[];this.m_depthBuffer=[];this.m_colorBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_groupBuffer=[];this.m_userDataBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_stuckThreshold=0;this.m_lastBodyContactStepBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_bodyContactCountBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_consecutiveContactStepsBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_stuckParticleBuffer=new b2GrowableBuffer(()=>0);this.m_proxyBuffer=new b2GrowableBuffer(()=>new b2ParticleSystem_Proxy());this.m_contactBuffer=new b2GrowableBuffer(()=>new b2ParticleContact());this.m_bodyContactBuffer=new b2GrowableBuffer(()=>new b2ParticleBodyContact());this.m_pairBuffer=new b2GrowableBuffer(()=>new b2ParticlePair());this.m_triadBuffer=new b2GrowableBuffer(()=>new b2ParticleTriad());this.m_expirationTimeBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_indexByExpirationTimeBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_timeElapsed=0;this.m_expirationTimeBufferRequiresSorting=false;this.m_groupCount=0;this.m_groupList=null;this.m_def=new b2ParticleSystemDef();this.m_prev=null;this.m_next=null;this.UpdateBodyContacts_callback=null;this.SolveCollision_callback=null;this.SetStrictContactCheck(def.strictContactCheck);this.SetDensity(def.density);this.SetGravityScale(def.gravityScale);this.SetRadius(def.radius);this.SetMaxParticleCount(def.maxCount);this.m_def=def.Clone();this.m_world=world;this.SetDestructionByAge(this.m_def.destroyByAge);}static computeTag(x,y){return (y+b2ParticleSystem.yOffset>>>0<<b2ParticleSystem.yShift)+(b2ParticleSystem.xScale*x+b2ParticleSystem.xOffset>>>0)>>>0;}static computeRelativeTag(tag,x,y){return tag+(y<<b2ParticleSystem.yShift)+(x<<b2ParticleSystem.xShift)>>>0;}Drop(){while(this.m_groupList){this.DestroyParticleGroup(this.m_groupList);}this.FreeUserOverridableBuffer(this.m_handleIndexBuffer);this.FreeUserOverridableBuffer(this.m_flagsBuffer);this.FreeUserOverridableBuffer(this.m_lastBodyContactStepBuffer);this.FreeUserOverridableBuffer(this.m_bodyContactCountBuffer);this.FreeUserOverridableBuffer(this.m_consecutiveContactStepsBuffer);this.FreeUserOverridableBuffer(this.m_positionBuffer);this.FreeUserOverridableBuffer(this.m_velocityBuffer);this.FreeUserOverridableBuffer(this.m_colorBuffer);this.FreeUserOverridableBuffer(this.m_userDataBuffer);this.FreeUserOverridableBuffer(this.m_expirationTimeBuffer);this.FreeUserOverridableBuffer(this.m_indexByExpirationTimeBuffer);this.FreeBuffer(this.m_forceBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_weightBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_staticPressureBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulationBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulation2Buffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_depthBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_groupBuffer,this.m_internalAllocatedCapacity);}CreateParticle(def){if(this.m_world.IsLocked()){throw new Error();}if(this.m_count>=this.m_internalAllocatedCapacity){const capacity=this.m_count?2*this.m_count:b2_minParticleSystemBufferCapacity;this.ReallocateInternalAllocatedBuffers(capacity);}if(this.m_count>=this.m_internalAllocatedCapacity){if(this.m_def.destroyByAge){this.DestroyOldestParticle(0,false);this.SolveZombie();}else {return b2_invalidParticleIndex;}}const index=this.m_count++;this.m_flagsBuffer.data[index]=0;if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[index]=0;}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[index]=0;}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[index]=0;}this.m_positionBuffer.data[index]=(this.m_positionBuffer.data[index]||new b2Vec2()).Copy(b2Maybe(def.position,b2Vec2.ZERO));this.m_velocityBuffer.data[index]=(this.m_velocityBuffer.data[index]||new b2Vec2()).Copy(b2Maybe(def.velocity,b2Vec2.ZERO));this.m_weightBuffer[index]=0;this.m_forceBuffer[index]=(this.m_forceBuffer[index]||new b2Vec2()).SetZero();if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[index]=0;}if(this.m_depthBuffer){this.m_depthBuffer[index]=0;}const color=new b2Color().Copy(b2Maybe(def.color,b2Color.ZERO));if(this.m_colorBuffer.data||!color.IsZero()){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);this.m_colorBuffer.data[index]=(this.m_colorBuffer.data[index]||new b2Color()).Copy(color);}if(this.m_userDataBuffer.data||def.userData){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);this.m_userDataBuffer.data[index]=def.userData;}if(this.m_handleIndexBuffer.data){this.m_handleIndexBuffer.data[index]=null;}const proxy=this.m_proxyBuffer.data[this.m_proxyBuffer.Append()];const lifetime=b2Maybe(def.lifetime,0.0);const finiteLifetime=lifetime>0.0;if(this.m_expirationTimeBuffer.data||finiteLifetime){this.SetParticleLifetime(index,finiteLifetime?lifetime:this.ExpirationTimeToLifetime(-this.GetQuantizedTimeElapsed()));this.m_indexByExpirationTimeBuffer.data[index]=index;}proxy.index=index;const group=b2Maybe(def.group,null);this.m_groupBuffer[index]=group;if(group){if(group.m_firstIndex<group.m_lastIndex){this.RotateBuffer(group.m_firstIndex,group.m_lastIndex,index);group.m_lastIndex=index+1;}else {group.m_firstIndex=index;group.m_lastIndex=index+1;}}this.SetParticleFlags(index,b2Maybe(def.flags,0));return index;}GetParticleHandleFromIndex(index){this.m_handleIndexBuffer.data=this.RequestBuffer(this.m_handleIndexBuffer.data);let handle=this.m_handleIndexBuffer.data[index];if(handle){return handle;}handle=new b2ParticleHandle();handle.SetIndex(index);this.m_handleIndexBuffer.data[index]=handle;return handle;}DestroyParticle(index,callDestructionListener=false){let flags=exports.b2ParticleFlag.b2_zombieParticle;if(callDestructionListener){flags|=exports.b2ParticleFlag.b2_destructionListenerParticle;}this.SetParticleFlags(index,this.m_flagsBuffer.data[index]|flags);}DestroyOldestParticle(index,callDestructionListener=false){const particleCount=this.GetParticleCount();const oldestFiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[particleCount-(index+1)];const oldestInfiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[index];this.DestroyParticle(this.m_expirationTimeBuffer.data[oldestFiniteLifetimeParticle]>0.0?oldestFiniteLifetimeParticle:oldestInfiniteLifetimeParticle,callDestructionListener);}DestroyParticlesInShape(shape,xf,callDestructionListener=false){const s_aabb=b2ParticleSystem.DestroyParticlesInShape_s_aabb;if(this.m_world.IsLocked()){throw new Error();}const callback=new b2ParticleSystem_DestroyParticlesInShapeCallback(this,shape,xf,callDestructionListener);const aabb=s_aabb;shape.ComputeAABB(aabb,xf,0);this.m_world.QueryAABB(callback,aabb);return callback.Destroyed();}CreateParticleGroup(groupDef){const s_transform=b2ParticleSystem.CreateParticleGroup_s_transform;if(this.m_world.IsLocked()){throw new Error();}const transform=s_transform;transform.SetPositionAngle(b2Maybe(groupDef.position,b2Vec2.ZERO),b2Maybe(groupDef.angle,0));const firstIndex=this.m_count;if(groupDef.shape){this.CreateParticlesWithShapeForGroup(groupDef.shape,groupDef,transform);}if(groupDef.shapes){this.CreateParticlesWithShapesForGroup(groupDef.shapes,b2Maybe(groupDef.shapeCount,groupDef.shapes.length),groupDef,transform);}if(groupDef.positionData){const count=b2Maybe(groupDef.particleCount,groupDef.positionData.length);for(let i=0;i<count;i++){const p=groupDef.positionData[i];this.CreateParticleForGroup(groupDef,transform,p);}}const lastIndex=this.m_count;let group=new b2ParticleGroup(this);group.m_firstIndex=firstIndex;group.m_lastIndex=lastIndex;group.m_strength=b2Maybe(groupDef.strength,1);group.m_userData=groupDef.userData;group.m_transform.Copy(transform);group.m_prev=null;group.m_next=this.m_groupList;if(this.m_groupList){this.m_groupList.m_prev=group;}this.m_groupList=group;++this.m_groupCount;for(let i=firstIndex;i<lastIndex;i++){this.m_groupBuffer[i]=group;}this.SetGroupFlags(group,b2Maybe(groupDef.groupFlags,0));const filter=new b2ParticleSystem_ConnectionFilter();this.UpdateContacts(true);this.UpdatePairsAndTriads(firstIndex,lastIndex,filter);if(groupDef.group){this.JoinParticleGroups(groupDef.group,group);group=groupDef.group;}return group;}JoinParticleGroups(groupA,groupB){if(this.m_world.IsLocked()){throw new Error();}this.RotateBuffer(groupB.m_firstIndex,groupB.m_lastIndex,this.m_count);this.RotateBuffer(groupA.m_firstIndex,groupA.m_lastIndex,groupB.m_firstIndex);const filter=new b2ParticleSystem_JoinParticleGroupsFilter(groupB.m_firstIndex);this.UpdateContacts(true);this.UpdatePairsAndTriads(groupA.m_firstIndex,groupB.m_lastIndex,filter);for(let i=groupB.m_firstIndex;i<groupB.m_lastIndex;i++){this.m_groupBuffer[i]=groupA;}const groupFlags=groupA.m_groupFlags|groupB.m_groupFlags;this.SetGroupFlags(groupA,groupFlags);groupA.m_lastIndex=groupB.m_lastIndex;groupB.m_firstIndex=groupB.m_lastIndex;this.DestroyParticleGroup(groupB);}SplitParticleGroup(group){this.UpdateContacts(true);const particleCount=group.GetParticleCount();const nodeBuffer=b2MakeArray(particleCount,index=>new b2ParticleSystem_ParticleListNode());b2ParticleSystem.InitializeParticleLists(group,nodeBuffer);this.MergeParticleListsInContact(group,nodeBuffer);const survivingList=b2ParticleSystem.FindLongestParticleList(group,nodeBuffer);this.MergeZombieParticleListNodes(group,nodeBuffer,survivingList);this.CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList);this.UpdatePairsAndTriadsWithParticleList(group,nodeBuffer);}GetParticleGroupList(){return this.m_groupList;}GetParticleGroupCount(){return this.m_groupCount;}GetParticleCount(){return this.m_count;}GetMaxParticleCount(){return this.m_def.maxCount;}SetMaxParticleCount(count){this.m_def.maxCount=count;}GetAllParticleFlags(){return this.m_allParticleFlags;}GetAllGroupFlags(){return this.m_allGroupFlags;}SetPaused(paused){this.m_paused=paused;}GetPaused(){return this.m_paused;}SetDensity(density){this.m_def.density=density;this.m_inverseDensity=1/this.m_def.density;}GetDensity(){return this.m_def.density;}SetGravityScale(gravityScale){this.m_def.gravityScale=gravityScale;}GetGravityScale(){return this.m_def.gravityScale;}SetDamping(damping){this.m_def.dampingStrength=damping;}GetDamping(){return this.m_def.dampingStrength;}SetStaticPressureIterations(iterations){this.m_def.staticPressureIterations=iterations;}GetStaticPressureIterations(){return this.m_def.staticPressureIterations;}SetRadius(radius){this.m_particleDiameter=2*radius;this.m_squaredDiameter=this.m_particleDiameter*this.m_particleDiameter;this.m_inverseDiameter=1/this.m_particleDiameter;}GetRadius(){return this.m_particleDiameter/2;}GetPositionBuffer(){return this.m_positionBuffer.data;}GetVelocityBuffer(){return this.m_velocityBuffer.data;}GetColorBuffer(){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);return this.m_colorBuffer.data;}GetGroupBuffer(){return this.m_groupBuffer;}GetWeightBuffer(){return this.m_weightBuffer;}GetUserDataBuffer(){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);return this.m_userDataBuffer.data;}GetFlagsBuffer(){return this.m_flagsBuffer.data;}SetParticleFlags(index,newFlags){const oldFlags=this.m_flagsBuffer.data[index];if(oldFlags&~newFlags){this.m_needsUpdateAllParticleFlags=true;}if(~this.m_allParticleFlags&newFlags){if(newFlags&exports.b2ParticleFlag.b2_tensileParticle){this.m_accumulation2Buffer=this.RequestBuffer(this.m_accumulation2Buffer);}if(newFlags&exports.b2ParticleFlag.b2_colorMixingParticle){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);}this.m_allParticleFlags|=newFlags;}this.m_flagsBuffer.data[index]=newFlags;}GetParticleFlags(index){return this.m_flagsBuffer.data[index];}SetFlagsBuffer(buffer){this.SetUserOverridableBuffer(this.m_flagsBuffer,buffer);}SetPositionBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}const count=buffer.length/2;const array=new Array(count);for(let i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_positionBuffer,buffer);}SetVelocityBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}const count=buffer.length/2;const array=new Array(count);for(let i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_velocityBuffer,buffer);}SetColorBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%4!==0){throw new Error();}const count=buffer.length/4;const array=new Array(count);for(let i=0;i<count;++i){array[i]=new b2Color(buffer.subarray(i*4,i*4+4));}buffer=array;}this.SetUserOverridableBuffer(this.m_colorBuffer,buffer);}SetUserDataBuffer(buffer){this.SetUserOverridableBuffer(this.m_userDataBuffer,buffer);}GetContacts(){return this.m_contactBuffer.data;}GetContactCount(){return this.m_contactBuffer.count;}GetBodyContacts(){return this.m_bodyContactBuffer.data;}GetBodyContactCount(){return this.m_bodyContactBuffer.count;}GetPairs(){return this.m_pairBuffer.data;}GetPairCount(){return this.m_pairBuffer.count;}GetTriads(){return this.m_triadBuffer.data;}GetTriadCount(){return this.m_triadBuffer.count;}SetStuckThreshold(steps){this.m_stuckThreshold=steps;if(steps>0){this.m_lastBodyContactStepBuffer.data=this.RequestBuffer(this.m_lastBodyContactStepBuffer.data);this.m_bodyContactCountBuffer.data=this.RequestBuffer(this.m_bodyContactCountBuffer.data);this.m_consecutiveContactStepsBuffer.data=this.RequestBuffer(this.m_consecutiveContactStepsBuffer.data);}}GetStuckCandidates(){return this.m_stuckParticleBuffer.Data();}GetStuckCandidateCount(){return this.m_stuckParticleBuffer.GetCount();}ComputeCollisionEnergy(){const s_v=b2ParticleSystem.ComputeCollisionEnergy_s_v;const vel_data=this.m_velocityBuffer.data;let sum_v2=0;for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const n=contact.normal;const v=b2Vec2.SubVV(vel_data[b],vel_data[a],s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){sum_v2+=vn*vn;}}return 0.5*this.GetParticleMass()*sum_v2;}SetStrictContactCheck(enabled){this.m_def.strictContactCheck=enabled;}GetStrictContactCheck(){return this.m_def.strictContactCheck;}SetParticleLifetime(index,lifetime){const initializeExpirationTimes=this.m_indexByExpirationTimeBuffer.data===null;this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);this.m_indexByExpirationTimeBuffer.data=this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data);if(initializeExpirationTimes){const particleCount=this.GetParticleCount();for(let i=0;i<particleCount;++i){this.m_indexByExpirationTimeBuffer.data[i]=i;}}const quantizedLifetime=lifetime/this.m_def.lifetimeGranularity;const newExpirationTime=quantizedLifetime>0.0?this.GetQuantizedTimeElapsed()+quantizedLifetime:quantizedLifetime;if(newExpirationTime!==this.m_expirationTimeBuffer.data[index]){this.m_expirationTimeBuffer.data[index]=newExpirationTime;this.m_expirationTimeBufferRequiresSorting=true;}}GetParticleLifetime(index){return this.ExpirationTimeToLifetime(this.GetExpirationTimeBuffer()[index]);}SetDestructionByAge(enable){if(enable){this.GetExpirationTimeBuffer();}this.m_def.destroyByAge=enable;}GetDestructionByAge(){return this.m_def.destroyByAge;}GetExpirationTimeBuffer(){this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);return this.m_expirationTimeBuffer.data;}ExpirationTimeToLifetime(expirationTime){return (expirationTime>0?expirationTime-this.GetQuantizedTimeElapsed():expirationTime)*this.m_def.lifetimeGranularity;}GetIndexByExpirationTimeBuffer(){if(this.GetParticleCount()){this.SetParticleLifetime(0,this.GetParticleLifetime(0));}else {this.m_indexByExpirationTimeBuffer.data=this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data);}return this.m_indexByExpirationTimeBuffer.data;}ParticleApplyLinearImpulse(index,impulse){this.ApplyLinearImpulse(index,index+1,impulse);}ApplyLinearImpulse(firstIndex,lastIndex,impulse){const vel_data=this.m_velocityBuffer.data;const numParticles=lastIndex-firstIndex;const totalMass=numParticles*this.GetParticleMass();const velocityDelta=new b2Vec2().Copy(impulse).SelfMul(1/totalMass);for(let i=firstIndex;i<lastIndex;i++){vel_data[i].SelfAdd(velocityDelta);}}static IsSignificantForce(force){return force.x!==0||force.y!==0;}ParticleApplyForce(index,force){if(b2ParticleSystem.IsSignificantForce(force)&&this.ForceCanBeApplied(this.m_flagsBuffer.data[index])){this.PrepareForceBuffer();this.m_forceBuffer[index].SelfAdd(force);}}ApplyForce(firstIndex,lastIndex,force){const distributedForce=new b2Vec2().Copy(force).SelfMul(1/(lastIndex-firstIndex));if(b2ParticleSystem.IsSignificantForce(distributedForce)){this.PrepareForceBuffer();for(let i=firstIndex;i<lastIndex;i++){this.m_forceBuffer[i].SelfAdd(distributedForce);}}}GetNext(){return this.m_next;}QueryAABB(callback,aabb){if(this.m_proxyBuffer.count===0){return;}const beginProxy=0;const endProxy=this.m_proxyBuffer.count;const firstProxy=std_lower_bound(this.m_proxyBuffer.data,beginProxy,endProxy,b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.lowerBound.x,this.m_inverseDiameter*aabb.lowerBound.y),b2ParticleSystem_Proxy.CompareProxyTag);const lastProxy=std_upper_bound(this.m_proxyBuffer.data,firstProxy,endProxy,b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.upperBound.x,this.m_inverseDiameter*aabb.upperBound.y),b2ParticleSystem_Proxy.CompareTagProxy);const pos_data=this.m_positionBuffer.data;for(let k=firstProxy;k<lastProxy;++k){const proxy=this.m_proxyBuffer.data[k];const i=proxy.index;const p=pos_data[i];if(aabb.lowerBound.x<p.x&&p.x<aabb.upperBound.x&&aabb.lowerBound.y<p.y&&p.y<aabb.upperBound.y){if(!callback.ReportParticle(this,i)){break;}}}}QueryShapeAABB(callback,shape,xf,childIndex=0){const s_aabb=b2ParticleSystem.QueryShapeAABB_s_aabb;const aabb=s_aabb;shape.ComputeAABB(aabb,xf,childIndex);this.QueryAABB(callback,aabb);}QueryPointAABB(callback,point,slop=b2_linearSlop){const s_aabb=b2ParticleSystem.QueryPointAABB_s_aabb;const aabb=s_aabb;aabb.lowerBound.Set(point.x-slop,point.y-slop);aabb.upperBound.Set(point.x+slop,point.y+slop);this.QueryAABB(callback,aabb);}RayCast(callback,point1,point2){const s_aabb=b2ParticleSystem.RayCast_s_aabb;const s_p=b2ParticleSystem.RayCast_s_p;const s_v=b2ParticleSystem.RayCast_s_v;const s_n=b2ParticleSystem.RayCast_s_n;const s_point=b2ParticleSystem.RayCast_s_point;if(this.m_proxyBuffer.count===0){return;}const pos_data=this.m_positionBuffer.data;const aabb=s_aabb;b2Vec2.MinV(point1,point2,aabb.lowerBound);b2Vec2.MaxV(point1,point2,aabb.upperBound);let fraction=1;const v=b2Vec2.SubVV(point2,point1,s_v);const v2=b2Vec2.DotVV(v,v);const enumerator=this.GetInsideBoundsEnumerator(aabb);let i;while((i=enumerator.GetNext())>=0){const p=b2Vec2.SubVV(point1,pos_data[i],s_p);const pv=b2Vec2.DotVV(p,v);const p2=b2Vec2.DotVV(p,p);const determinant=pv*pv-v2*(p2-this.m_squaredDiameter);if(determinant>=0){const sqrtDeterminant=b2Sqrt(determinant);let t=(-pv-sqrtDeterminant)/v2;if(t>fraction){continue;}if(t<0){t=(-pv+sqrtDeterminant)/v2;if(t<0||t>fraction){continue;}}const n=b2Vec2.AddVMulSV(p,t,v,s_n);n.Normalize();const f=callback.ReportParticle(this,i,b2Vec2.AddVMulSV(point1,t,v,s_point),n,t);fraction=b2Min(fraction,f);if(fraction<=0){break;}}}}ComputeAABB(aabb){const particleCount=this.GetParticleCount();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;const pos_data=this.m_positionBuffer.data;for(let i=0;i<particleCount;i++){const p=pos_data[i];b2Vec2.MinV(aabb.lowerBound,p,aabb.lowerBound);b2Vec2.MaxV(aabb.upperBound,p,aabb.upperBound);}aabb.lowerBound.x-=this.m_particleDiameter;aabb.lowerBound.y-=this.m_particleDiameter;aabb.upperBound.x+=this.m_particleDiameter;aabb.upperBound.y+=this.m_particleDiameter;}FreeBuffer(b,capacity){if(b===null){return;}b.length=0;}FreeUserOverridableBuffer(b){if(b.userSuppliedCapacity===0){this.FreeBuffer(b.data,this.m_internalAllocatedCapacity);}}ReallocateBuffer3(oldBuffer,oldCapacity,newCapacity){if(newCapacity<=oldCapacity){throw new Error();}const newBuffer=oldBuffer?oldBuffer.slice():[];newBuffer.length=newCapacity;return newBuffer;}ReallocateBuffer5(buffer,userSuppliedCapacity,oldCapacity,newCapacity,deferred){if(newCapacity<=oldCapacity){throw new Error();}if(!(!userSuppliedCapacity||newCapacity<=userSuppliedCapacity)){throw new Error();}if((!deferred||buffer)&&!userSuppliedCapacity){buffer=this.ReallocateBuffer3(buffer,oldCapacity,newCapacity);}return buffer;}ReallocateBuffer4(buffer,oldCapacity,newCapacity,deferred){return this.ReallocateBuffer5(buffer.data,buffer.userSuppliedCapacity,oldCapacity,newCapacity,deferred);}RequestBuffer(buffer){if(!buffer){if(this.m_internalAllocatedCapacity===0){this.ReallocateInternalAllocatedBuffers(b2_minParticleSystemBufferCapacity);}buffer=[];buffer.length=this.m_internalAllocatedCapacity;}return buffer;}ReallocateHandleBuffers(newCapacity){this.m_handleIndexBuffer.data=this.ReallocateBuffer4(this.m_handleIndexBuffer,this.m_internalAllocatedCapacity,newCapacity,true);}ReallocateInternalAllocatedBuffers(capacity){function LimitCapacity(capacity,maxCount){return maxCount&&capacity>maxCount?maxCount:capacity;}capacity=LimitCapacity(capacity,this.m_def.maxCount);capacity=LimitCapacity(capacity,this.m_flagsBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_positionBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_velocityBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_colorBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_userDataBuffer.userSuppliedCapacity);if(this.m_internalAllocatedCapacity<capacity){this.ReallocateHandleBuffers(capacity);this.m_flagsBuffer.data=this.ReallocateBuffer4(this.m_flagsBuffer,this.m_internalAllocatedCapacity,capacity,false);const stuck=this.m_stuckThreshold>0;this.m_lastBodyContactStepBuffer.data=this.ReallocateBuffer4(this.m_lastBodyContactStepBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_bodyContactCountBuffer.data=this.ReallocateBuffer4(this.m_bodyContactCountBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_consecutiveContactStepsBuffer.data=this.ReallocateBuffer4(this.m_consecutiveContactStepsBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_positionBuffer.data=this.ReallocateBuffer4(this.m_positionBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_velocityBuffer.data=this.ReallocateBuffer4(this.m_velocityBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_forceBuffer=this.ReallocateBuffer5(this.m_forceBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_weightBuffer=this.ReallocateBuffer5(this.m_weightBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_staticPressureBuffer=this.ReallocateBuffer5(this.m_staticPressureBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_accumulationBuffer=this.ReallocateBuffer5(this.m_accumulationBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_accumulation2Buffer=this.ReallocateBuffer5(this.m_accumulation2Buffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_depthBuffer=this.ReallocateBuffer5(this.m_depthBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_colorBuffer.data=this.ReallocateBuffer4(this.m_colorBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_groupBuffer=this.ReallocateBuffer5(this.m_groupBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_userDataBuffer.data=this.ReallocateBuffer4(this.m_userDataBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_expirationTimeBuffer.data=this.ReallocateBuffer4(this.m_expirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_indexByExpirationTimeBuffer.data=this.ReallocateBuffer4(this.m_indexByExpirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_internalAllocatedCapacity=capacity;}}CreateParticleForGroup(groupDef,xf,p){const particleDef=new b2ParticleDef();particleDef.flags=b2Maybe(groupDef.flags,0);b2Transform.MulXV(xf,p,particleDef.position);b2Vec2.AddVV(b2Maybe(groupDef.linearVelocity,b2Vec2.ZERO),b2Vec2.CrossSV(b2Maybe(groupDef.angularVelocity,0),b2Vec2.SubVV(particleDef.position,b2Maybe(groupDef.position,b2Vec2.ZERO),b2Vec2.s_t0),b2Vec2.s_t0),particleDef.velocity);particleDef.color.Copy(b2Maybe(groupDef.color,b2Color.ZERO));particleDef.lifetime=b2Maybe(groupDef.lifetime,0);particleDef.userData=groupDef.userData;this.CreateParticle(particleDef);}CreateParticlesStrokeShapeForGroup(shape,groupDef,xf){const s_edge=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge;const s_d=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d;const s_p=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p;let stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}let positionOnEdge=0;const childCount=shape.GetChildCount();for(let childIndex=0;childIndex<childCount;childIndex++){let edge=null;if(shape.GetType()===exports.b2ShapeType.e_edgeShape){edge=shape;}else {edge=s_edge;shape.GetChildEdge(edge,childIndex);}const d=b2Vec2.SubVV(edge.m_vertex2,edge.m_vertex1,s_d);const edgeLength=d.Length();while(positionOnEdge<edgeLength){const p=b2Vec2.AddVMulSV(edge.m_vertex1,positionOnEdge/edgeLength,d,s_p);this.CreateParticleForGroup(groupDef,xf,p);positionOnEdge+=stride;}positionOnEdge-=edgeLength;}}CreateParticlesFillShapeForGroup(shape,groupDef,xf){const s_aabb=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb;const s_p=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p;let stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}const identity=b2Transform.IDENTITY;const aabb=s_aabb;shape.ComputeAABB(aabb,identity,0);for(let y=Math.floor(aabb.lowerBound.y/stride)*stride;y<aabb.upperBound.y;y+=stride){for(let x=Math.floor(aabb.lowerBound.x/stride)*stride;x<aabb.upperBound.x;x+=stride){const p=s_p.Set(x,y);if(shape.TestPoint(identity,p)){this.CreateParticleForGroup(groupDef,xf,p);}}}}CreateParticlesWithShapeForGroup(shape,groupDef,xf){switch(shape.GetType()){case exports.b2ShapeType.e_edgeShape:case exports.b2ShapeType.e_chainShape:this.CreateParticlesStrokeShapeForGroup(shape,groupDef,xf);break;case exports.b2ShapeType.e_polygonShape:case exports.b2ShapeType.e_circleShape:this.CreateParticlesFillShapeForGroup(shape,groupDef,xf);break;}}CreateParticlesWithShapesForGroup(shapes,shapeCount,groupDef,xf){const compositeShape=new b2ParticleSystem_CompositeShape(shapes,shapeCount);this.CreateParticlesFillShapeForGroup(compositeShape,groupDef,xf);}CloneParticle(oldIndex,group){const def=new b2ParticleDef();def.flags=this.m_flagsBuffer.data[oldIndex];def.position.Copy(this.m_positionBuffer.data[oldIndex]);def.velocity.Copy(this.m_velocityBuffer.data[oldIndex]);if(this.m_colorBuffer.data){def.color.Copy(this.m_colorBuffer.data[oldIndex]);}if(this.m_userDataBuffer.data){def.userData=this.m_userDataBuffer.data[oldIndex];}def.group=group;const newIndex=this.CreateParticle(def);if(this.m_handleIndexBuffer.data){const handle=this.m_handleIndexBuffer.data[oldIndex];if(handle){handle.SetIndex(newIndex);}this.m_handleIndexBuffer.data[newIndex]=handle;this.m_handleIndexBuffer.data[oldIndex]=null;}if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[newIndex]=this.m_lastBodyContactStepBuffer.data[oldIndex];}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[newIndex]=this.m_bodyContactCountBuffer.data[oldIndex];}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[newIndex]=this.m_consecutiveContactStepsBuffer.data[oldIndex];}if(this.m_hasForce){this.m_forceBuffer[newIndex].Copy(this.m_forceBuffer[oldIndex]);}if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[newIndex]=this.m_staticPressureBuffer[oldIndex];}if(this.m_depthBuffer){this.m_depthBuffer[newIndex]=this.m_depthBuffer[oldIndex];}if(this.m_expirationTimeBuffer.data){this.m_expirationTimeBuffer.data[newIndex]=this.m_expirationTimeBuffer.data[oldIndex];}return newIndex;}DestroyParticlesInGroup(group,callDestructionListener=false){for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){this.DestroyParticle(i,callDestructionListener);}}DestroyParticleGroup(group){if(this.m_world.m_destructionListener){this.m_world.m_destructionListener.SayGoodbyeParticleGroup(group);}this.SetGroupFlags(group,0);for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){this.m_groupBuffer[i]=null;}if(group.m_prev){group.m_prev.m_next=group.m_next;}if(group.m_next){group.m_next.m_prev=group.m_prev;}if(group===this.m_groupList){this.m_groupList=group.m_next;}--this.m_groupCount;}static ParticleCanBeConnected(flags,group){return (flags&(exports.b2ParticleFlag.b2_wallParticle|exports.b2ParticleFlag.b2_springParticle|exports.b2ParticleFlag.b2_elasticParticle))!==0||group!==null&&(group.GetGroupFlags()&exports.b2ParticleGroupFlag.b2_rigidParticleGroup)!==0;}UpdatePairsAndTriads(firstIndex,lastIndex,filter){const s_dab=b2ParticleSystem.UpdatePairsAndTriads_s_dab;const s_dbc=b2ParticleSystem.UpdatePairsAndTriads_s_dbc;const s_dca=b2ParticleSystem.UpdatePairsAndTriads_s_dca;const pos_data=this.m_positionBuffer.data;let particleFlags=0;for(let i=firstIndex;i<lastIndex;i++){particleFlags|=this.m_flagsBuffer.data[i];}if(particleFlags&b2ParticleSystem.k_pairFlags){for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const af=this.m_flagsBuffer.data[a];const bf=this.m_flagsBuffer.data[b];const groupA=this.m_groupBuffer[a];const groupB=this.m_groupBuffer[b];if(a>=firstIndex&&a<lastIndex&&b>=firstIndex&&b<lastIndex&&!((af|bf)&exports.b2ParticleFlag.b2_zombieParticle)&&(af|bf)&b2ParticleSystem.k_pairFlags&&(filter.IsNecessary(a)||filter.IsNecessary(b))&&b2ParticleSystem.ParticleCanBeConnected(af,groupA)&&b2ParticleSystem.ParticleCanBeConnected(bf,groupB)&&filter.ShouldCreatePair(a,b)){const pair=this.m_pairBuffer.data[this.m_pairBuffer.Append()];pair.indexA=a;pair.indexB=b;pair.flags=contact.flags;pair.strength=b2Min(groupA?groupA.m_strength:1,groupB?groupB.m_strength:1);pair.distance=b2Vec2.DistanceVV(pos_data[a],pos_data[b]);}std_stable_sort(this.m_pairBuffer.data,0,this.m_pairBuffer.count,b2ParticleSystem.ComparePairIndices);this.m_pairBuffer.Unique(b2ParticleSystem.MatchPairIndices);}}if(particleFlags&b2ParticleSystem.k_triadFlags){const diagram=new b2VoronoiDiagram(lastIndex-firstIndex);for(let i=firstIndex;i<lastIndex;i++){const flags=this.m_flagsBuffer.data[i];const group=this.m_groupBuffer[i];if(!(flags&exports.b2ParticleFlag.b2_zombieParticle)&&b2ParticleSystem.ParticleCanBeConnected(flags,group)){diagram.AddGenerator(pos_data[i],i,filter.IsNecessary(i));}}const stride=this.GetParticleStride();diagram.Generate(stride/2,stride*2);const system=this;const callback=(a,b,c)=>{const af=system.m_flagsBuffer.data[a];const bf=system.m_flagsBuffer.data[b];const cf=system.m_flagsBuffer.data[c];if((af|bf|cf)&b2ParticleSystem.k_triadFlags&&filter.ShouldCreateTriad(a,b,c)){const pa=pos_data[a];const pb=pos_data[b];const pc=pos_data[c];const dab=b2Vec2.SubVV(pa,pb,s_dab);const dbc=b2Vec2.SubVV(pb,pc,s_dbc);const dca=b2Vec2.SubVV(pc,pa,s_dca);const maxDistanceSquared=b2_maxTriadDistanceSquared*system.m_squaredDiameter;if(b2Vec2.DotVV(dab,dab)>maxDistanceSquared||b2Vec2.DotVV(dbc,dbc)>maxDistanceSquared||b2Vec2.DotVV(dca,dca)>maxDistanceSquared){return;}const groupA=system.m_groupBuffer[a];const groupB=system.m_groupBuffer[b];const groupC=system.m_groupBuffer[c];const triad=system.m_triadBuffer.data[system.m_triadBuffer.Append()];triad.indexA=a;triad.indexB=b;triad.indexC=c;triad.flags=af|bf|cf;triad.strength=b2Min(b2Min(groupA?groupA.m_strength:1,groupB?groupB.m_strength:1),groupC?groupC.m_strength:1);const midPoint_x=(pa.x+pb.x+pc.x)/3.0;const midPoint_y=(pa.y+pb.y+pc.y)/3.0;triad.pa.x=pa.x-midPoint_x;triad.pa.y=pa.y-midPoint_y;triad.pb.x=pb.x-midPoint_x;triad.pb.y=pb.y-midPoint_y;triad.pc.x=pc.x-midPoint_x;triad.pc.y=pc.y-midPoint_y;triad.ka=-b2Vec2.DotVV(dca,dab);triad.kb=-b2Vec2.DotVV(dab,dbc);triad.kc=-b2Vec2.DotVV(dbc,dca);triad.s=b2Vec2.CrossVV(pa,pb)+b2Vec2.CrossVV(pb,pc)+b2Vec2.CrossVV(pc,pa);}};diagram.GetNodes(callback);std_stable_sort(this.m_triadBuffer.data,0,this.m_triadBuffer.count,b2ParticleSystem.CompareTriadIndices);this.m_triadBuffer.Unique(b2ParticleSystem.MatchTriadIndices);}}UpdatePairsAndTriadsWithReactiveParticles(){const filter=new b2ParticleSystem_ReactiveFilter(this.m_flagsBuffer);this.UpdatePairsAndTriads(0,this.m_count,filter);for(let i=0;i<this.m_count;i++){this.m_flagsBuffer.data[i]&=~exports.b2ParticleFlag.b2_reactiveParticle;}this.m_allParticleFlags&=~exports.b2ParticleFlag.b2_reactiveParticle;}static ComparePairIndices(a,b){const diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}return a.indexB<b.indexB;}static MatchPairIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB;}static CompareTriadIndices(a,b){const diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}const diffB=a.indexB-b.indexB;if(diffB!==0){return diffB<0;}return a.indexC<b.indexC;}static MatchTriadIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB&&a.indexC===b.indexC;}static InitializeParticleLists(group,nodeBuffer){const bufferIndex=group.GetBufferIndex();const particleCount=group.GetParticleCount();for(let i=0;i<particleCount;i++){const node=nodeBuffer[i];node.list=node;node.next=null;node.count=1;node.index=i+bufferIndex;}}MergeParticleListsInContact(group,nodeBuffer){const bufferIndex=group.GetBufferIndex();for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;if(!group.ContainsParticle(a)||!group.ContainsParticle(b)){continue;}let listA=nodeBuffer[a-bufferIndex].list;let listB=nodeBuffer[b-bufferIndex].list;if(listA===listB){continue;}if(listA.count<listB.count){const _tmp=listA;listA=listB;listB=_tmp;}b2ParticleSystem.MergeParticleLists(listA,listB);}}static MergeParticleLists(listA,listB){for(let b=listB;;){b.list=listA;const nextB=b.next;if(nextB){b=nextB;}else {b.next=listA.next;break;}}listA.next=listB;listA.count+=listB.count;listB.count=0;}static FindLongestParticleList(group,nodeBuffer){const particleCount=group.GetParticleCount();let result=nodeBuffer[0];for(let i=0;i<particleCount;i++){const node=nodeBuffer[i];if(result.count<node.count){result=node;}}return result;}MergeZombieParticleListNodes(group,nodeBuffer,survivingList){const particleCount=group.GetParticleCount();for(let i=0;i<particleCount;i++){const node=nodeBuffer[i];if(node!==survivingList&&this.m_flagsBuffer.data[node.index]&exports.b2ParticleFlag.b2_zombieParticle){b2ParticleSystem.MergeParticleListAndNode(survivingList,node);}}}static MergeParticleListAndNode(list,node){node.list=list;node.next=list.next;list.next=node;list.count++;node.count=0;}CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList){const particleCount=group.GetParticleCount();const def=new b2ParticleGroupDef();def.groupFlags=group.GetGroupFlags();def.userData=group.GetUserData();for(let i=0;i<particleCount;i++){const list=nodeBuffer[i];if(!list.count||list===survivingList){continue;}const newGroup=this.CreateParticleGroup(def);for(let node=list;node;node=node.next){const oldIndex=node.index;const newIndex=this.CloneParticle(oldIndex,newGroup);this.m_flagsBuffer.data[oldIndex]|=exports.b2ParticleFlag.b2_zombieParticle;node.index=newIndex;}}}UpdatePairsAndTriadsWithParticleList(group,nodeBuffer){const bufferIndex=group.GetBufferIndex();for(let k=0;k<this.m_pairBuffer.count;k++){const pair=this.m_pairBuffer.data[k];const a=pair.indexA;const b=pair.indexB;if(group.ContainsParticle(a)){pair.indexA=nodeBuffer[a-bufferIndex].index;}if(group.ContainsParticle(b)){pair.indexB=nodeBuffer[b-bufferIndex].index;}}for(let k=0;k<this.m_triadBuffer.count;k++){const triad=this.m_triadBuffer.data[k];const a=triad.indexA;const b=triad.indexB;const c=triad.indexC;if(group.ContainsParticle(a)){triad.indexA=nodeBuffer[a-bufferIndex].index;}if(group.ContainsParticle(b)){triad.indexB=nodeBuffer[b-bufferIndex].index;}if(group.ContainsParticle(c)){triad.indexC=nodeBuffer[c-bufferIndex].index;}}}ComputeDepth(){const contactGroups=[];let contactGroupsCount=0;for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const groupA=this.m_groupBuffer[a];const groupB=this.m_groupBuffer[b];if(groupA&&groupA===groupB&&groupA.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){contactGroups[contactGroupsCount++]=contact;}}const groupsToUpdate=[];let groupsToUpdateCount=0;for(let group=this.m_groupList;group;group=group.GetNext()){if(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){groupsToUpdate[groupsToUpdateCount++]=group;this.SetGroupFlags(group,group.m_groupFlags&~exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth);for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){this.m_accumulationBuffer[i]=0;}}}for(let k=0;k<contactGroupsCount;k++){const contact=contactGroups[k];const a=contact.indexA;const b=contact.indexB;const w=contact.weight;this.m_accumulationBuffer[a]+=w;this.m_accumulationBuffer[b]+=w;}for(let i=0;i<groupsToUpdateCount;i++){const group=groupsToUpdate[i];for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){const w=this.m_accumulationBuffer[i];this.m_depthBuffer[i]=w<0.8?0:b2_maxFloat;}}const iterationCount=b2Sqrt(this.m_count)>>0;for(let t=0;t<iterationCount;t++){let updated=false;for(let k=0;k<contactGroupsCount;k++){const contact=contactGroups[k];const a=contact.indexA;const b=contact.indexB;const r=1-contact.weight;const ap0=this.m_depthBuffer[a];const bp0=this.m_depthBuffer[b];const ap1=bp0+r;const bp1=ap0+r;if(ap0>ap1){this.m_depthBuffer[a]=ap1;updated=true;}if(bp0>bp1){this.m_depthBuffer[b]=bp1;updated=true;}}if(!updated){break;}}for(let i=0;i<groupsToUpdateCount;i++){const group=groupsToUpdate[i];for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){if(this.m_depthBuffer[i]<b2_maxFloat){this.m_depthBuffer[i]*=this.m_particleDiameter;}else {this.m_depthBuffer[i]=0;}}}}GetInsideBoundsEnumerator(aabb){const lowerTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.lowerBound.x-1,this.m_inverseDiameter*aabb.lowerBound.y-1);const upperTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.upperBound.x+1,this.m_inverseDiameter*aabb.upperBound.y+1);const beginProxy=0;const endProxy=this.m_proxyBuffer.count;const firstProxy=std_lower_bound(this.m_proxyBuffer.data,beginProxy,endProxy,lowerTag,b2ParticleSystem_Proxy.CompareProxyTag);const lastProxy=std_upper_bound(this.m_proxyBuffer.data,beginProxy,endProxy,upperTag,b2ParticleSystem_Proxy.CompareTagProxy);return new b2ParticleSystem_InsideBoundsEnumerator(this,lowerTag,upperTag,firstProxy,lastProxy);}UpdateAllParticleFlags(){this.m_allParticleFlags=0;for(let i=0;i<this.m_count;i++){this.m_allParticleFlags|=this.m_flagsBuffer.data[i];}this.m_needsUpdateAllParticleFlags=false;}UpdateAllGroupFlags(){this.m_allGroupFlags=0;for(let group=this.m_groupList;group;group=group.GetNext()){this.m_allGroupFlags|=group.m_groupFlags;}this.m_needsUpdateAllGroupFlags=false;}AddContact(a,b,contacts){const flags_data=this.m_flagsBuffer.data;const pos_data=this.m_positionBuffer.data;const d=b2Vec2.SubVV(pos_data[b],pos_data[a],b2ParticleSystem.AddContact_s_d);const distBtParticlesSq=b2Vec2.DotVV(d,d);if(0<distBtParticlesSq&&distBtParticlesSq<this.m_squaredDiameter){const invD=b2InvSqrt(distBtParticlesSq);const contact=this.m_contactBuffer.data[this.m_contactBuffer.Append()];contact.indexA=a;contact.indexB=b;contact.flags=flags_data[a]|flags_data[b];contact.weight=1-distBtParticlesSq*invD*this.m_inverseDiameter;contact.normal.x=invD*d.x;contact.normal.y=invD*d.y;}}FindContacts_Reference(contacts){const beginProxy=0;const endProxy=this.m_proxyBuffer.count;this.m_contactBuffer.count=0;for(let a=beginProxy,c=beginProxy;a<endProxy;a++){const rightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,0);for(let b=a+1;b<endProxy;b++){if(rightTag<this.m_proxyBuffer.data[b].tag){break;}this.AddContact(this.m_proxyBuffer.data[a].index,this.m_proxyBuffer.data[b].index,this.m_contactBuffer);}const bottomLeftTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,-1,1);for(;c<endProxy;c++){if(bottomLeftTag<=this.m_proxyBuffer.data[c].tag){break;}}const bottomRightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,1);for(let b=c;b<endProxy;b++){if(bottomRightTag<this.m_proxyBuffer.data[b].tag){break;}this.AddContact(this.m_proxyBuffer.data[a].index,this.m_proxyBuffer.data[b].index,this.m_contactBuffer);}}}FindContacts(contacts){this.FindContacts_Reference(contacts);}UpdateProxies_Reference(proxies){const pos_data=this.m_positionBuffer.data;const inv_diam=this.m_inverseDiameter;for(let k=0;k<this.m_proxyBuffer.count;++k){const proxy=this.m_proxyBuffer.data[k];const i=proxy.index;const p=pos_data[i];proxy.tag=b2ParticleSystem.computeTag(inv_diam*p.x,inv_diam*p.y);}}UpdateProxies(proxies){this.UpdateProxies_Reference(proxies);}SortProxies(proxies){std_sort$1(this.m_proxyBuffer.data,0,this.m_proxyBuffer.count,b2ParticleSystem_Proxy.CompareProxyProxy);}FilterContacts(contacts){const contactFilter=this.GetParticleContactFilter();if(contactFilter===null){return;}const system=this;const predicate=contact=>{return (contact.flags&exports.b2ParticleFlag.b2_particleContactFilterParticle)!==0&&!contactFilter.ShouldCollideParticleParticle(system,contact.indexA,contact.indexB);};this.m_contactBuffer.RemoveIf(predicate);}NotifyContactListenerPreContact(particlePairs){const contactListener=this.GetParticleContactListener();if(contactListener===null){return;}particlePairs.Initialize(this.m_contactBuffer,this.m_flagsBuffer);throw new Error();}NotifyContactListenerPostContact(particlePairs){const contactListener=this.GetParticleContactListener();if(contactListener===null){return;}for(let k=0;k<this.m_contactBuffer.count;++k){const contact=this.m_contactBuffer.data[k];{contactListener.BeginContactParticleParticle(this,contact);}}throw new Error();}static b2ParticleContactIsZombie(contact){return (contact.flags&exports.b2ParticleFlag.b2_zombieParticle)===exports.b2ParticleFlag.b2_zombieParticle;}UpdateContacts(exceptZombie){this.UpdateProxies(this.m_proxyBuffer);this.SortProxies(this.m_proxyBuffer);const particlePairs=new b2ParticlePairSet();this.NotifyContactListenerPreContact(particlePairs);this.FindContacts(this.m_contactBuffer);this.FilterContacts(this.m_contactBuffer);this.NotifyContactListenerPostContact(particlePairs);if(exceptZombie){this.m_contactBuffer.RemoveIf(b2ParticleSystem.b2ParticleContactIsZombie);}}NotifyBodyContactListenerPreContact(fixtureSet){const contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}fixtureSet.Initialize(this.m_bodyContactBuffer,this.m_flagsBuffer);throw new Error();}NotifyBodyContactListenerPostContact(fixtureSet){const contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];{contactListener.BeginContactFixtureParticle(this,contact);}}throw new Error();}UpdateBodyContacts(){const s_aabb=b2ParticleSystem.UpdateBodyContacts_s_aabb;const fixtureSet=new b2ParticleSystem_FixtureParticleSet();this.NotifyBodyContactListenerPreContact(fixtureSet);if(this.m_stuckThreshold>0){const particleCount=this.GetParticleCount();for(let i=0;i<particleCount;i++){this.m_bodyContactCountBuffer.data[i]=0;if(this.m_timestamp>this.m_lastBodyContactStepBuffer.data[i]+1){this.m_consecutiveContactStepsBuffer.data[i]=0;}}}this.m_bodyContactBuffer.SetCount(0);this.m_stuckParticleBuffer.SetCount(0);const aabb=s_aabb;this.ComputeAABB(aabb);if(this.UpdateBodyContacts_callback===null){this.UpdateBodyContacts_callback=new b2ParticleSystem_UpdateBodyContactsCallback(this);}const callback=this.UpdateBodyContacts_callback;callback.m_contactFilter=this.GetFixtureContactFilter();this.m_world.QueryAABB(callback,aabb);if(this.m_def.strictContactCheck){this.RemoveSpuriousBodyContacts();}this.NotifyBodyContactListenerPostContact(fixtureSet);}Solve(step){const s_subStep=b2ParticleSystem.Solve_s_subStep;if(this.m_count===0){return;}if(this.m_expirationTimeBuffer.data){this.SolveLifetimes(step);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_zombieParticle){this.SolveZombie();}if(this.m_needsUpdateAllParticleFlags){this.UpdateAllParticleFlags();}if(this.m_needsUpdateAllGroupFlags){this.UpdateAllGroupFlags();}if(this.m_paused){return;}for(this.m_iterationIndex=0;this.m_iterationIndex<step.particleIterations;this.m_iterationIndex++){++this.m_timestamp;const subStep=s_subStep.Copy(step);subStep.dt/=step.particleIterations;subStep.inv_dt*=step.particleIterations;this.UpdateContacts(false);this.UpdateBodyContacts();this.ComputeWeight();if(this.m_allGroupFlags&exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){this.ComputeDepth();}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_reactiveParticle){this.UpdatePairsAndTriadsWithReactiveParticles();}if(this.m_hasForce){this.SolveForce(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_viscousParticle){this.SolveViscous();}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_repulsiveParticle){this.SolveRepulsive(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_powderParticle){this.SolvePowder(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_tensileParticle){this.SolveTensile(subStep);}if(this.m_allGroupFlags&exports.b2ParticleGroupFlag.b2_solidParticleGroup){this.SolveSolid(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_colorMixingParticle){this.SolveColorMixing();}this.SolveGravity(subStep);if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_staticPressureParticle){this.SolveStaticPressure(subStep);}this.SolvePressure(subStep);this.SolveDamping(subStep);if(this.m_allParticleFlags&b2ParticleSystem.k_extraDampingFlags){this.SolveExtraDamping();}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_elasticParticle){this.SolveElastic(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_springParticle){this.SolveSpring(subStep);}this.LimitVelocity(subStep);if(this.m_allGroupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup){this.SolveRigidDamping();}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_barrierParticle){this.SolveBarrier(subStep);}this.SolveCollision(subStep);if(this.m_allGroupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup){this.SolveRigid(subStep);}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_wallParticle){this.SolveWall();}for(let i=0;i<this.m_count;i++){this.m_positionBuffer.data[i].SelfMulAdd(subStep.dt,this.m_velocityBuffer.data[i]);}}}SolveCollision(step){const s_aabb=b2ParticleSystem.SolveCollision_s_aabb;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const aabb=s_aabb;aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;for(let i=0;i<this.m_count;i++){const v=vel_data[i];const p1=pos_data[i];const p2_x=p1.x+step.dt*v.x;const p2_y=p1.y+step.dt*v.y;aabb.lowerBound.x=b2Min(aabb.lowerBound.x,b2Min(p1.x,p2_x));aabb.lowerBound.y=b2Min(aabb.lowerBound.y,b2Min(p1.y,p2_y));aabb.upperBound.x=b2Max(aabb.upperBound.x,b2Max(p1.x,p2_x));aabb.upperBound.y=b2Max(aabb.upperBound.y,b2Max(p1.y,p2_y));}if(this.SolveCollision_callback===null){this.SolveCollision_callback=new b2ParticleSystem_SolveCollisionCallback(this,step);}const callback=this.SolveCollision_callback;callback.m_step=step;this.m_world.QueryAABB(callback,aabb);}LimitVelocity(step){const vel_data=this.m_velocityBuffer.data;const criticalVelocitySquared=this.GetCriticalVelocitySquared(step);for(let i=0;i<this.m_count;i++){const v=vel_data[i];const v2=b2Vec2.DotVV(v,v);if(v2>criticalVelocitySquared){v.SelfMul(b2Sqrt(criticalVelocitySquared/v2));}}}SolveGravity(step){const s_gravity=b2ParticleSystem.SolveGravity_s_gravity;const vel_data=this.m_velocityBuffer.data;const gravity=b2Vec2.MulSV(step.dt*this.m_def.gravityScale,this.m_world.GetGravity(),s_gravity);for(let i=0;i<this.m_count;i++){vel_data[i].SelfAdd(gravity);}}SolveBarrier(step){const s_aabb=b2ParticleSystem.SolveBarrier_s_aabb;const s_va=b2ParticleSystem.SolveBarrier_s_va;const s_vb=b2ParticleSystem.SolveBarrier_s_vb;const s_pba=b2ParticleSystem.SolveBarrier_s_pba;const s_vba=b2ParticleSystem.SolveBarrier_s_vba;const s_vc=b2ParticleSystem.SolveBarrier_s_vc;const s_pca=b2ParticleSystem.SolveBarrier_s_pca;const s_vca=b2ParticleSystem.SolveBarrier_s_vca;const s_qba=b2ParticleSystem.SolveBarrier_s_qba;const s_qca=b2ParticleSystem.SolveBarrier_s_qca;const s_dv=b2ParticleSystem.SolveBarrier_s_dv;const s_f=b2ParticleSystem.SolveBarrier_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;for(let i=0;i<this.m_count;i++){const flags=this.m_flagsBuffer.data[i];if((flags&b2ParticleSystem.k_barrierWallFlags)!==0){vel_data[i].SetZero();}}const tmax=b2_barrierCollisionTime*step.dt;const mass=this.GetParticleMass();for(let k=0;k<this.m_pairBuffer.count;k++){const pair=this.m_pairBuffer.data[k];if(pair.flags&exports.b2ParticleFlag.b2_barrierParticle){const a=pair.indexA;const b=pair.indexB;const pa=pos_data[a];const pb=pos_data[b];const aabb=s_aabb;b2Vec2.MinV(pa,pb,aabb.lowerBound);b2Vec2.MaxV(pa,pb,aabb.upperBound);const aGroup=this.m_groupBuffer[a];const bGroup=this.m_groupBuffer[b];const va=this.GetLinearVelocity(aGroup,a,pa,s_va);const vb=this.GetLinearVelocity(bGroup,b,pb,s_vb);const pba=b2Vec2.SubVV(pb,pa,s_pba);const vba=b2Vec2.SubVV(vb,va,s_vba);const enumerator=this.GetInsideBoundsEnumerator(aabb);let c;while((c=enumerator.GetNext())>=0){const pc=pos_data[c];const cGroup=this.m_groupBuffer[c];if(aGroup!==cGroup&&bGroup!==cGroup){const vc=this.GetLinearVelocity(cGroup,c,pc,s_vc);const pca=b2Vec2.SubVV(pc,pa,s_pca);const vca=b2Vec2.SubVV(vc,va,s_vca);const e2=b2Vec2.CrossVV(vba,vca);const e1=b2Vec2.CrossVV(pba,vca)-b2Vec2.CrossVV(pca,vba);const e0=b2Vec2.CrossVV(pba,pca);let s,t;const qba=s_qba,qca=s_qca;if(e2===0){if(e1===0){continue;}t=-e0/e1;if(!(t>=0&&t<tmax)){continue;}b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(s>=0&&s<=1)){continue;}}else {const det=e1*e1-4*e0*e2;if(det<0){continue;}const sqrtDet=b2Sqrt(det);let t1=(-e1-sqrtDet)/(2*e2);let t2=(-e1+sqrtDet)/(2*e2);if(t1>t2){const tmp=t1;t1=t2;t2=tmp;}t=t1;b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(t>=0&&t<tmax&&s>=0&&s<=1)){t=t2;if(!(t>=0&&t<tmax)){continue;}b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(s>=0&&s<=1)){continue;}}}const dv=s_dv;dv.x=va.x+s*vba.x-vc.x;dv.y=va.y+s*vba.y-vc.y;const f=b2Vec2.MulSV(mass,dv,s_f);if(cGroup&&this.IsRigidGroup(cGroup)){const mass=cGroup.GetMass();const inertia=cGroup.GetInertia();if(mass>0){cGroup.m_linearVelocity.SelfMulAdd(1/mass,f);}if(inertia>0){cGroup.m_angularVelocity+=b2Vec2.CrossVV(b2Vec2.SubVV(pc,cGroup.GetCenter(),b2Vec2.s_t0),f)/inertia;}}else {vel_data[c].SelfAdd(dv);}this.ParticleApplyForce(c,f.SelfMul(-step.inv_dt));}}}}}SolveStaticPressure(step){this.m_staticPressureBuffer=this.RequestBuffer(this.m_staticPressureBuffer);const criticalPressure=this.GetCriticalPressure(step);const pressurePerWeight=this.m_def.staticPressureStrength*criticalPressure;const maxPressure=b2_maxParticlePressure*criticalPressure;const relaxation=this.m_def.staticPressureRelaxation;for(let t=0;t<this.m_def.staticPressureIterations;t++){for(let i=0;i<this.m_count;i++){this.m_accumulationBuffer[i]=0;}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_staticPressureParticle){const a=contact.indexA;const b=contact.indexB;const w=contact.weight;this.m_accumulationBuffer[a]+=w*this.m_staticPressureBuffer[b];this.m_accumulationBuffer[b]+=w*this.m_staticPressureBuffer[a];}}for(let i=0;i<this.m_count;i++){const w=this.m_weightBuffer[i];if(this.m_flagsBuffer.data[i]&exports.b2ParticleFlag.b2_staticPressureParticle){const wh=this.m_accumulationBuffer[i];const h=(wh+pressurePerWeight*(w-b2_minParticleWeight))/(w+relaxation);this.m_staticPressureBuffer[i]=b2Clamp(h,0.0,maxPressure);}else {this.m_staticPressureBuffer[i]=0;}}}}ComputeWeight(){for(let k=0;k<this.m_count;k++){this.m_weightBuffer[k]=0;}for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;const w=contact.weight;this.m_weightBuffer[a]+=w;}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const w=contact.weight;this.m_weightBuffer[a]+=w;this.m_weightBuffer[b]+=w;}}SolvePressure(step){const s_f=b2ParticleSystem.SolvePressure_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const criticalPressure=this.GetCriticalPressure(step);const pressurePerWeight=this.m_def.pressureStrength*criticalPressure;const maxPressure=b2_maxParticlePressure*criticalPressure;for(let i=0;i<this.m_count;i++){const w=this.m_weightBuffer[i];const h=pressurePerWeight*b2Max(0.0,w-b2_minParticleWeight);this.m_accumulationBuffer[i]=b2Min(h,maxPressure);}if(this.m_allParticleFlags&b2ParticleSystem.k_noPressureFlags){for(let i=0;i<this.m_count;i++){if(this.m_flagsBuffer.data[i]&b2ParticleSystem.k_noPressureFlags){this.m_accumulationBuffer[i]=0;}}}if(this.m_allParticleFlags&exports.b2ParticleFlag.b2_staticPressureParticle){for(let i=0;i<this.m_count;i++){if(this.m_flagsBuffer.data[i]&exports.b2ParticleFlag.b2_staticPressureParticle){this.m_accumulationBuffer[i]+=this.m_staticPressureBuffer[i];}}}const velocityPerPressure=step.dt/(this.m_def.density*this.m_particleDiameter);const inv_mass=this.GetParticleInvMass();for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;const b=contact.body;const w=contact.weight;const m=contact.mass;const n=contact.normal;const p=pos_data[a];const h=this.m_accumulationBuffer[a]+pressurePerWeight*w;const f=b2Vec2.MulSV(velocityPerPressure*w*m*h,n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const w=contact.weight;const n=contact.normal;const h=this.m_accumulationBuffer[a]+this.m_accumulationBuffer[b];const f=b2Vec2.MulSV(velocityPerPressure*w*h,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}SolveDamping(step){const s_v=b2ParticleSystem.SolveDamping_s_v;const s_f=b2ParticleSystem.SolveDamping_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const linearDamping=this.m_def.dampingStrength;const quadraticDamping=1/this.GetCriticalVelocity(step);const inv_mass=this.GetParticleInvMass();for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;const b=contact.body;const w=contact.weight;const m=contact.mass;const n=contact.normal;const p=pos_data[a];const v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){const damping=b2Max(linearDamping*w,b2Min(-quadraticDamping*vn,0.5));const f=b2Vec2.MulSV(damping*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const w=contact.weight;const n=contact.normal;const v=b2Vec2.SubVV(vel_data[b],vel_data[a],s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){const damping=b2Max(linearDamping*w,b2Min(-quadraticDamping*vn,0.5));const f=b2Vec2.MulSV(damping*vn,n,s_f);vel_data[a].SelfAdd(f);vel_data[b].SelfSub(f);}}}SolveRigidDamping(){const s_t0=b2ParticleSystem.SolveRigidDamping_s_t0;const s_t1=b2ParticleSystem.SolveRigidDamping_s_t1;const s_p=b2ParticleSystem.SolveRigidDamping_s_p;const s_v=b2ParticleSystem.SolveRigidDamping_s_v;const invMassA=[0.0],invInertiaA=[0.0],tangentDistanceA=[0.0];const invMassB=[0.0],invInertiaB=[0.0],tangentDistanceB=[0.0];const pos_data=this.m_positionBuffer.data;const damping=this.m_def.dampingStrength;for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;const aGroup=this.m_groupBuffer[a];if(aGroup&&this.IsRigidGroup(aGroup)){const b=contact.body;const n=contact.normal;const w=contact.weight;const p=pos_data[a];const v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,s_t0),aGroup.GetLinearVelocityFromWorldPoint(p,s_t1),s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){this.InitDampingParameterWithRigidGroupOrParticle(invMassA,invInertiaA,tangentDistanceA,true,aGroup,a,p,n);this.InitDampingParameter(invMassB,invInertiaB,tangentDistanceB,b.GetMass(),b.GetInertia()-b.GetMass()*b.GetLocalCenter().LengthSquared(),b.GetWorldCenter(),p,n);const f=damping*b2Min(w,1.0)*this.ComputeDampingImpulse(invMassA[0],invInertiaA[0],tangentDistanceA[0],invMassB[0],invInertiaB[0],tangentDistanceB[0],vn);this.ApplyDamping(invMassA[0],invInertiaA[0],tangentDistanceA[0],true,aGroup,a,f,n);b.ApplyLinearImpulse(b2Vec2.MulSV(-f,n,b2Vec2.s_t0),p,true);}}}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;const n=contact.normal;const w=contact.weight;const aGroup=this.m_groupBuffer[a];const bGroup=this.m_groupBuffer[b];const aRigid=this.IsRigidGroup(aGroup);const bRigid=this.IsRigidGroup(bGroup);if(aGroup!==bGroup&&(aRigid||bRigid)){const p=b2Vec2.MidVV(pos_data[a],pos_data[b],s_p);const v=b2Vec2.SubVV(this.GetLinearVelocity(bGroup,b,p,s_t0),this.GetLinearVelocity(aGroup,a,p,s_t1),s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){this.InitDampingParameterWithRigidGroupOrParticle(invMassA,invInertiaA,tangentDistanceA,aRigid,aGroup,a,p,n);this.InitDampingParameterWithRigidGroupOrParticle(invMassB,invInertiaB,tangentDistanceB,bRigid,bGroup,b,p,n);const f=damping*w*this.ComputeDampingImpulse(invMassA[0],invInertiaA[0],tangentDistanceA[0],invMassB[0],invInertiaB[0],tangentDistanceB[0],vn);this.ApplyDamping(invMassA[0],invInertiaA[0],tangentDistanceA[0],aRigid,aGroup,a,f,n);this.ApplyDamping(invMassB[0],invInertiaB[0],tangentDistanceB[0],bRigid,bGroup,b,-f,n);}}}}SolveExtraDamping(){const s_v=b2ParticleSystem.SolveExtraDamping_s_v;const s_f=b2ParticleSystem.SolveExtraDamping_s_f;const vel_data=this.m_velocityBuffer.data;const pos_data=this.m_positionBuffer.data;const inv_mass=this.GetParticleInvMass();for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;if(this.m_flagsBuffer.data[a]&b2ParticleSystem.k_extraDampingFlags){const b=contact.body;const m=contact.mass;const n=contact.normal;const p=pos_data[a];const v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);const vn=b2Vec2.DotVV(v,n);if(vn<0){const f=b2Vec2.MulSV(0.5*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}}}SolveWall(){const vel_data=this.m_velocityBuffer.data;for(let i=0;i<this.m_count;i++){if(this.m_flagsBuffer.data[i]&exports.b2ParticleFlag.b2_wallParticle){vel_data[i].SetZero();}}}SolveRigid(step){const s_position=b2ParticleSystem.SolveRigid_s_position;const s_rotation=b2ParticleSystem.SolveRigid_s_rotation;const s_transform=b2ParticleSystem.SolveRigid_s_transform;const s_velocityTransform=b2ParticleSystem.SolveRigid_s_velocityTransform;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;for(let group=this.m_groupList;group;group=group.GetNext()){if(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup){group.UpdateStatistics();const rotation=s_rotation;rotation.SetAngle(step.dt*group.m_angularVelocity);const position=b2Vec2.AddVV(group.m_center,b2Vec2.SubVV(b2Vec2.MulSV(step.dt,group.m_linearVelocity,b2Vec2.s_t0),b2Rot.MulRV(rotation,group.m_center,b2Vec2.s_t1),b2Vec2.s_t0),s_position);const transform=s_transform;transform.SetPositionRotation(position,rotation);b2Transform.MulXX(transform,group.m_transform,group.m_transform);const velocityTransform=s_velocityTransform;velocityTransform.p.x=step.inv_dt*transform.p.x;velocityTransform.p.y=step.inv_dt*transform.p.y;velocityTransform.q.s=step.inv_dt*transform.q.s;velocityTransform.q.c=step.inv_dt*(transform.q.c-1);for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){b2Transform.MulXV(velocityTransform,pos_data[i],vel_data[i]);}}}}SolveElastic(step){const s_pa=b2ParticleSystem.SolveElastic_s_pa;const s_pb=b2ParticleSystem.SolveElastic_s_pb;const s_pc=b2ParticleSystem.SolveElastic_s_pc;const s_r=b2ParticleSystem.SolveElastic_s_r;const s_t0=b2ParticleSystem.SolveElastic_s_t0;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const elasticStrength=step.inv_dt*this.m_def.elasticStrength;for(let k=0;k<this.m_triadBuffer.count;k++){const triad=this.m_triadBuffer.data[k];if(triad.flags&exports.b2ParticleFlag.b2_elasticParticle){const a=triad.indexA;const b=triad.indexB;const c=triad.indexC;const oa=triad.pa;const ob=triad.pb;const oc=triad.pc;const pa=s_pa.Copy(pos_data[a]);const pb=s_pb.Copy(pos_data[b]);const pc=s_pc.Copy(pos_data[c]);const va=vel_data[a];const vb=vel_data[b];const vc=vel_data[c];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);pc.SelfMulAdd(step.dt,vc);const midPoint_x=(pa.x+pb.x+pc.x)/3.0;const midPoint_y=(pa.y+pb.y+pc.y)/3.0;pa.x-=midPoint_x;pa.y-=midPoint_y;pb.x-=midPoint_x;pb.y-=midPoint_y;pc.x-=midPoint_x;pc.y-=midPoint_y;const r=s_r;r.s=b2Vec2.CrossVV(oa,pa)+b2Vec2.CrossVV(ob,pb)+b2Vec2.CrossVV(oc,pc);r.c=b2Vec2.DotVV(oa,pa)+b2Vec2.DotVV(ob,pb)+b2Vec2.DotVV(oc,pc);const r2=r.s*r.s+r.c*r.c;let invR=b2InvSqrt(r2);if(!isFinite(invR)){invR=1.98177537e+019;}r.s*=invR;r.c*=invR;const strength=elasticStrength*triad.strength;b2Rot.MulRV(r,oa,s_t0);b2Vec2.SubVV(s_t0,pa,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);va.SelfAdd(s_t0);b2Rot.MulRV(r,ob,s_t0);b2Vec2.SubVV(s_t0,pb,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);vb.SelfAdd(s_t0);b2Rot.MulRV(r,oc,s_t0);b2Vec2.SubVV(s_t0,pc,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);vc.SelfAdd(s_t0);}}}SolveSpring(step){const s_pa=b2ParticleSystem.SolveSpring_s_pa;const s_pb=b2ParticleSystem.SolveSpring_s_pb;const s_d=b2ParticleSystem.SolveSpring_s_d;const s_f=b2ParticleSystem.SolveSpring_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const springStrength=step.inv_dt*this.m_def.springStrength;for(let k=0;k<this.m_pairBuffer.count;k++){const pair=this.m_pairBuffer.data[k];if(pair.flags&exports.b2ParticleFlag.b2_springParticle){const a=pair.indexA;const b=pair.indexB;const pa=s_pa.Copy(pos_data[a]);const pb=s_pb.Copy(pos_data[b]);const va=vel_data[a];const vb=vel_data[b];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);const d=b2Vec2.SubVV(pb,pa,s_d);const r0=pair.distance;const r1=d.Length();const strength=springStrength*pair.strength;const f=b2Vec2.MulSV(strength*(r0-r1)/r1,d,s_f);va.SelfSub(f);vb.SelfAdd(f);}}}SolveTensile(step){const s_weightedNormal=b2ParticleSystem.SolveTensile_s_weightedNormal;const s_s=b2ParticleSystem.SolveTensile_s_s;const s_f=b2ParticleSystem.SolveTensile_s_f;const vel_data=this.m_velocityBuffer.data;for(let i=0;i<this.m_count;i++){this.m_accumulation2Buffer[i]=new b2Vec2();this.m_accumulation2Buffer[i].SetZero();}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_tensileParticle){const a=contact.indexA;const b=contact.indexB;const w=contact.weight;const n=contact.normal;const weightedNormal=b2Vec2.MulSV((1-w)*w,n,s_weightedNormal);this.m_accumulation2Buffer[a].SelfSub(weightedNormal);this.m_accumulation2Buffer[b].SelfAdd(weightedNormal);}}const criticalVelocity=this.GetCriticalVelocity(step);const pressureStrength=this.m_def.surfaceTensionPressureStrength*criticalVelocity;const normalStrength=this.m_def.surfaceTensionNormalStrength*criticalVelocity;const maxVelocityVariation=b2_maxParticleForce*criticalVelocity;for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_tensileParticle){const a=contact.indexA;const b=contact.indexB;const w=contact.weight;const n=contact.normal;const h=this.m_weightBuffer[a]+this.m_weightBuffer[b];const s=b2Vec2.SubVV(this.m_accumulation2Buffer[b],this.m_accumulation2Buffer[a],s_s);const fn=b2Min(pressureStrength*(h-2)+normalStrength*b2Vec2.DotVV(s,n),maxVelocityVariation)*w;const f=b2Vec2.MulSV(fn,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}SolveViscous(){const s_v=b2ParticleSystem.SolveViscous_s_v;const s_f=b2ParticleSystem.SolveViscous_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const viscousStrength=this.m_def.viscousStrength;const inv_mass=this.GetParticleInvMass();for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;if(this.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_viscousParticle){const b=contact.body;const w=contact.weight;const m=contact.mass;const p=pos_data[a];const v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);const f=b2Vec2.MulSV(viscousStrength*m*w,v,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_viscousParticle){const a=contact.indexA;const b=contact.indexB;const w=contact.weight;const v=b2Vec2.SubVV(vel_data[b],vel_data[a],s_v);const f=b2Vec2.MulSV(viscousStrength*w,v,s_f);vel_data[a].SelfAdd(f);vel_data[b].SelfSub(f);}}}SolveRepulsive(step){const s_f=b2ParticleSystem.SolveRepulsive_s_f;const vel_data=this.m_velocityBuffer.data;const repulsiveStrength=this.m_def.repulsiveStrength*this.GetCriticalVelocity(step);for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_repulsiveParticle){const a=contact.indexA;const b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){const w=contact.weight;const n=contact.normal;const f=b2Vec2.MulSV(repulsiveStrength*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}}SolvePowder(step){const s_f=b2ParticleSystem.SolvePowder_s_f;const pos_data=this.m_positionBuffer.data;const vel_data=this.m_velocityBuffer.data;const powderStrength=this.m_def.powderStrength*this.GetCriticalVelocity(step);const minWeight=1.0-b2_particleStride;const inv_mass=this.GetParticleInvMass();for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];const a=contact.index;if(this.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_powderParticle){const w=contact.weight;if(w>minWeight){const b=contact.body;const m=contact.mass;const p=pos_data[a];const n=contact.normal;const f=b2Vec2.MulSV(powderStrength*m*(w-minWeight),n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}}}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];if(contact.flags&exports.b2ParticleFlag.b2_powderParticle){const w=contact.weight;if(w>minWeight){const a=contact.indexA;const b=contact.indexB;const n=contact.normal;const f=b2Vec2.MulSV(powderStrength*(w-minWeight),n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}}SolveSolid(step){const s_f=b2ParticleSystem.SolveSolid_s_f;const vel_data=this.m_velocityBuffer.data;this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);const ejectionStrength=step.inv_dt*this.m_def.ejectionStrength;for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){const w=contact.weight;const n=contact.normal;const h=this.m_depthBuffer[a]+this.m_depthBuffer[b];const f=b2Vec2.MulSV(ejectionStrength*h*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}SolveForce(step){const vel_data=this.m_velocityBuffer.data;const velocityPerForce=step.dt*this.GetParticleInvMass();for(let i=0;i<this.m_count;i++){vel_data[i].SelfMulAdd(velocityPerForce,this.m_forceBuffer[i]);}this.m_hasForce=false;}SolveColorMixing(){const colorMixing=0.5*this.m_def.colorMixingStrength;if(colorMixing){for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];const a=contact.indexA;const b=contact.indexB;if(this.m_flagsBuffer.data[a]&this.m_flagsBuffer.data[b]&exports.b2ParticleFlag.b2_colorMixingParticle){const colorA=this.m_colorBuffer.data[a];const colorB=this.m_colorBuffer.data[b];b2Color.MixColors(colorA,colorB,colorMixing);}}}}SolveZombie(){let newCount=0;const newIndices=[];for(let i=0;i<this.m_count;i++){newIndices[i]=b2_invalidParticleIndex;}let allParticleFlags=0;for(let i=0;i<this.m_count;i++){const flags=this.m_flagsBuffer.data[i];if(flags&exports.b2ParticleFlag.b2_zombieParticle){const destructionListener=this.m_world.m_destructionListener;if(flags&exports.b2ParticleFlag.b2_destructionListenerParticle&&destructionListener){destructionListener.SayGoodbyeParticle(this,i);}if(this.m_handleIndexBuffer.data){const handle=this.m_handleIndexBuffer.data[i];if(handle){handle.SetIndex(b2_invalidParticleIndex);this.m_handleIndexBuffer.data[i]=null;}}newIndices[i]=b2_invalidParticleIndex;}else {newIndices[i]=newCount;if(i!==newCount){if(this.m_handleIndexBuffer.data){const handle=this.m_handleIndexBuffer.data[i];if(handle){handle.SetIndex(newCount);}this.m_handleIndexBuffer.data[newCount]=handle;}this.m_flagsBuffer.data[newCount]=this.m_flagsBuffer.data[i];if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[newCount]=this.m_lastBodyContactStepBuffer.data[i];}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[newCount]=this.m_bodyContactCountBuffer.data[i];}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[newCount]=this.m_consecutiveContactStepsBuffer.data[i];}this.m_positionBuffer.data[newCount].Copy(this.m_positionBuffer.data[i]);this.m_velocityBuffer.data[newCount].Copy(this.m_velocityBuffer.data[i]);this.m_groupBuffer[newCount]=this.m_groupBuffer[i];if(this.m_hasForce){this.m_forceBuffer[newCount].Copy(this.m_forceBuffer[i]);}if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[newCount]=this.m_staticPressureBuffer[i];}if(this.m_depthBuffer){this.m_depthBuffer[newCount]=this.m_depthBuffer[i];}if(this.m_colorBuffer.data){this.m_colorBuffer.data[newCount].Copy(this.m_colorBuffer.data[i]);}if(this.m_userDataBuffer.data){this.m_userDataBuffer.data[newCount]=this.m_userDataBuffer.data[i];}if(this.m_expirationTimeBuffer.data){this.m_expirationTimeBuffer.data[newCount]=this.m_expirationTimeBuffer.data[i];}}newCount++;allParticleFlags|=flags;}}const Test={IsProxyInvalid:proxy=>{return proxy.index<0;},IsContactInvalid:contact=>{return contact.indexA<0||contact.indexB<0;},IsBodyContactInvalid:contact=>{return contact.index<0;},IsPairInvalid:pair=>{return pair.indexA<0||pair.indexB<0;},IsTriadInvalid:triad=>{return triad.indexA<0||triad.indexB<0||triad.indexC<0;}};for(let k=0;k<this.m_proxyBuffer.count;k++){const proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices[proxy.index];}this.m_proxyBuffer.RemoveIf(Test.IsProxyInvalid);for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];contact.indexA=newIndices[contact.indexA];contact.indexB=newIndices[contact.indexB];}this.m_contactBuffer.RemoveIf(Test.IsContactInvalid);for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];contact.index=newIndices[contact.index];}this.m_bodyContactBuffer.RemoveIf(Test.IsBodyContactInvalid);for(let k=0;k<this.m_pairBuffer.count;k++){const pair=this.m_pairBuffer.data[k];pair.indexA=newIndices[pair.indexA];pair.indexB=newIndices[pair.indexB];}this.m_pairBuffer.RemoveIf(Test.IsPairInvalid);for(let k=0;k<this.m_triadBuffer.count;k++){const triad=this.m_triadBuffer.data[k];triad.indexA=newIndices[triad.indexA];triad.indexB=newIndices[triad.indexB];triad.indexC=newIndices[triad.indexC];}this.m_triadBuffer.RemoveIf(Test.IsTriadInvalid);if(this.m_indexByExpirationTimeBuffer.data){let writeOffset=0;for(let readOffset=0;readOffset<this.m_count;readOffset++){const newIndex=newIndices[this.m_indexByExpirationTimeBuffer.data[readOffset]];if(newIndex!==b2_invalidParticleIndex){this.m_indexByExpirationTimeBuffer.data[writeOffset++]=newIndex;}}}for(let group=this.m_groupList;group;group=group.GetNext()){let firstIndex=newCount;let lastIndex=0;let modified=false;for(let i=group.m_firstIndex;i<group.m_lastIndex;i++){const j=newIndices[i];if(j>=0){firstIndex=b2Min(firstIndex,j);lastIndex=b2Max(lastIndex,j+1);}else {modified=true;}}if(firstIndex<lastIndex){group.m_firstIndex=firstIndex;group.m_lastIndex=lastIndex;if(modified){if(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_solidParticleGroup){this.SetGroupFlags(group,group.m_groupFlags|exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth);}}}else {group.m_firstIndex=0;group.m_lastIndex=0;if(!(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupCanBeEmpty)){this.SetGroupFlags(group,group.m_groupFlags|exports.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed);}}}this.m_count=newCount;this.m_allParticleFlags=allParticleFlags;this.m_needsUpdateAllParticleFlags=false;for(let group=this.m_groupList;group;){const next=group.GetNext();if(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed){this.DestroyParticleGroup(group);}group=next;}}SolveLifetimes(step){this.m_timeElapsed=this.LifetimeToExpirationTime(step.dt);const quantizedTimeElapsed=this.GetQuantizedTimeElapsed();const expirationTimes=this.m_expirationTimeBuffer.data;const expirationTimeIndices=this.m_indexByExpirationTimeBuffer.data;const particleCount=this.GetParticleCount();if(this.m_expirationTimeBufferRequiresSorting){const ExpirationTimeComparator=(particleIndexA,particleIndexB)=>{const expirationTimeA=expirationTimes[particleIndexA];const expirationTimeB=expirationTimes[particleIndexB];const infiniteExpirationTimeA=expirationTimeA<=0.0;const infiniteExpirationTimeB=expirationTimeB<=0.0;return infiniteExpirationTimeA===infiniteExpirationTimeB?expirationTimeA>expirationTimeB:infiniteExpirationTimeA;};std_sort$1(expirationTimeIndices,0,particleCount,ExpirationTimeComparator);this.m_expirationTimeBufferRequiresSorting=false;}for(let i=particleCount-1;i>=0;--i){const particleIndex=expirationTimeIndices[i];const expirationTime=expirationTimes[particleIndex];if(quantizedTimeElapsed<expirationTime||expirationTime<=0){break;}this.DestroyParticle(particleIndex);}}RotateBuffer(start,mid,end){if(start===mid||mid===end){return;}function newIndices(i){if(i<start){return i;}else if(i<mid){return i+end-mid;}else if(i<end){return i+start-mid;}else {return i;}}std_rotate(this.m_flagsBuffer.data,start,mid,end);if(this.m_lastBodyContactStepBuffer.data){std_rotate(this.m_lastBodyContactStepBuffer.data,start,mid,end);}if(this.m_bodyContactCountBuffer.data){std_rotate(this.m_bodyContactCountBuffer.data,start,mid,end);}if(this.m_consecutiveContactStepsBuffer.data){std_rotate(this.m_consecutiveContactStepsBuffer.data,start,mid,end);}std_rotate(this.m_positionBuffer.data,start,mid,end);std_rotate(this.m_velocityBuffer.data,start,mid,end);std_rotate(this.m_groupBuffer,start,mid,end);if(this.m_hasForce){std_rotate(this.m_forceBuffer,start,mid,end);}if(this.m_staticPressureBuffer){std_rotate(this.m_staticPressureBuffer,start,mid,end);}if(this.m_depthBuffer){std_rotate(this.m_depthBuffer,start,mid,end);}if(this.m_colorBuffer.data){std_rotate(this.m_colorBuffer.data,start,mid,end);}if(this.m_userDataBuffer.data){std_rotate(this.m_userDataBuffer.data,start,mid,end);}if(this.m_handleIndexBuffer.data){std_rotate(this.m_handleIndexBuffer.data,start,mid,end);for(let i=start;i<end;++i){const handle=this.m_handleIndexBuffer.data[i];if(handle){handle.SetIndex(newIndices(handle.GetIndex()));}}}if(this.m_expirationTimeBuffer.data){std_rotate(this.m_expirationTimeBuffer.data,start,mid,end);const particleCount=this.GetParticleCount();const indexByExpirationTime=this.m_indexByExpirationTimeBuffer.data;for(let i=0;i<particleCount;++i){indexByExpirationTime[i]=newIndices(indexByExpirationTime[i]);}}for(let k=0;k<this.m_proxyBuffer.count;k++){const proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices(proxy.index);}for(let k=0;k<this.m_contactBuffer.count;k++){const contact=this.m_contactBuffer.data[k];contact.indexA=newIndices(contact.indexA);contact.indexB=newIndices(contact.indexB);}for(let k=0;k<this.m_bodyContactBuffer.count;k++){const contact=this.m_bodyContactBuffer.data[k];contact.index=newIndices(contact.index);}for(let k=0;k<this.m_pairBuffer.count;k++){const pair=this.m_pairBuffer.data[k];pair.indexA=newIndices(pair.indexA);pair.indexB=newIndices(pair.indexB);}for(let k=0;k<this.m_triadBuffer.count;k++){const triad=this.m_triadBuffer.data[k];triad.indexA=newIndices(triad.indexA);triad.indexB=newIndices(triad.indexB);triad.indexC=newIndices(triad.indexC);}for(let group=this.m_groupList;group;group=group.GetNext()){group.m_firstIndex=newIndices(group.m_firstIndex);group.m_lastIndex=newIndices(group.m_lastIndex-1)+1;}}GetCriticalVelocity(step){return this.m_particleDiameter*step.inv_dt;}GetCriticalVelocitySquared(step){const velocity=this.GetCriticalVelocity(step);return velocity*velocity;}GetCriticalPressure(step){return this.m_def.density*this.GetCriticalVelocitySquared(step);}GetParticleStride(){return b2_particleStride*this.m_particleDiameter;}GetParticleMass(){const stride=this.GetParticleStride();return this.m_def.density*stride*stride;}GetParticleInvMass(){const inverseStride=this.m_inverseDiameter*(1.0/b2_particleStride);return this.m_inverseDensity*inverseStride*inverseStride;}GetFixtureContactFilter(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_fixtureContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;}GetParticleContactFilter(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_particleContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;}GetFixtureContactListener(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_fixtureContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;}GetParticleContactListener(){return this.m_allParticleFlags&exports.b2ParticleFlag.b2_particleContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;}SetUserOverridableBuffer(buffer,data){buffer.data=data;buffer.userSuppliedCapacity=data.length;}SetGroupFlags(group,newFlags){const oldFlags=group.m_groupFlags;if((oldFlags^newFlags)&exports.b2ParticleGroupFlag.b2_solidParticleGroup){newFlags|=exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth;}if(oldFlags&~newFlags){this.m_needsUpdateAllGroupFlags=true;}if(~this.m_allGroupFlags&newFlags){if(newFlags&exports.b2ParticleGroupFlag.b2_solidParticleGroup){this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);}this.m_allGroupFlags|=newFlags;}group.m_groupFlags=newFlags;}static BodyContactCompare(lhs,rhs){if(lhs.index===rhs.index){return lhs.weight>rhs.weight;}return lhs.index<rhs.index;}RemoveSpuriousBodyContacts(){std_sort$1(this.m_bodyContactBuffer.data,0,this.m_bodyContactBuffer.count,b2ParticleSystem.BodyContactCompare);const s_n=b2ParticleSystem.RemoveSpuriousBodyContacts_s_n;const s_pos=b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos;const s_normal=b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal;const k_maxContactsPerPoint=3;const system=this;let lastIndex=-1;let currentContacts=0;const b2ParticleBodyContactRemovePredicate=contact=>{if(contact.index!==lastIndex){currentContacts=0;lastIndex=contact.index;}if(currentContacts++>k_maxContactsPerPoint){return true;}const n=s_n.Copy(contact.normal);n.SelfMul(system.m_particleDiameter*(1-contact.weight));const pos=b2Vec2.AddVV(system.m_positionBuffer.data[contact.index],n,s_pos);if(!contact.fixture.TestPoint(pos)){const childCount=contact.fixture.GetShape().GetChildCount();for(let childIndex=0;childIndex<childCount;childIndex++){const normal=s_normal;const distance=contact.fixture.ComputeDistance(pos,normal,childIndex);if(distance<b2_linearSlop){return false;}}return true;}return false;};this.m_bodyContactBuffer.count=std_remove_if(this.m_bodyContactBuffer.data,b2ParticleBodyContactRemovePredicate,this.m_bodyContactBuffer.count);}DetectStuckParticle(particle){if(this.m_stuckThreshold<=0){return;}++this.m_bodyContactCountBuffer.data[particle];if(this.m_bodyContactCountBuffer.data[particle]===2){++this.m_consecutiveContactStepsBuffer.data[particle];if(this.m_consecutiveContactStepsBuffer.data[particle]>this.m_stuckThreshold){this.m_stuckParticleBuffer.data[this.m_stuckParticleBuffer.Append()]=particle;}}this.m_lastBodyContactStepBuffer.data[particle]=this.m_timestamp;}ValidateParticleIndex(index){return index>=0&&index<this.GetParticleCount()&&index!==b2_invalidParticleIndex;}GetQuantizedTimeElapsed(){return Math.floor(this.m_timeElapsed/0x100000000);}LifetimeToExpirationTime(lifetime){return this.m_timeElapsed+Math.floor(lifetime/this.m_def.lifetimeGranularity*0x100000000);}ForceCanBeApplied(flags){return !(flags&exports.b2ParticleFlag.b2_wallParticle);}PrepareForceBuffer(){if(!this.m_hasForce){for(let i=0;i<this.m_count;i++){this.m_forceBuffer[i].SetZero();}this.m_hasForce=true;}}IsRigidGroup(group){return group!==null&&(group.m_groupFlags&exports.b2ParticleGroupFlag.b2_rigidParticleGroup)!==0;}GetLinearVelocity(group,particleIndex,point,out){if(group&&this.IsRigidGroup(group)){return group.GetLinearVelocityFromWorldPoint(point,out);}else {return out.Copy(this.m_velocityBuffer.data[particleIndex]);}}InitDampingParameter(invMass,invInertia,tangentDistance,mass,inertia,center,point,normal){invMass[0]=mass>0?1/mass:0;invInertia[0]=inertia>0?1/inertia:0;tangentDistance[0]=b2Vec2.CrossVV(b2Vec2.SubVV(point,center,b2Vec2.s_t0),normal);}InitDampingParameterWithRigidGroupOrParticle(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,point,normal){if(group&&isRigidGroup){this.InitDampingParameter(invMass,invInertia,tangentDistance,group.GetMass(),group.GetInertia(),group.GetCenter(),point,normal);}else {const flags=this.m_flagsBuffer.data[particleIndex];this.InitDampingParameter(invMass,invInertia,tangentDistance,flags&exports.b2ParticleFlag.b2_wallParticle?0:this.GetParticleMass(),0,point,point,normal);}}ComputeDampingImpulse(invMassA,invInertiaA,tangentDistanceA,invMassB,invInertiaB,tangentDistanceB,normalVelocity){const invMass=invMassA+invInertiaA*tangentDistanceA*tangentDistanceA+invMassB+invInertiaB*tangentDistanceB*tangentDistanceB;return invMass>0?normalVelocity/invMass:0;}ApplyDamping(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,impulse,normal){if(group&&isRigidGroup){group.m_linearVelocity.SelfMulAdd(impulse*invMass,normal);group.m_angularVelocity+=impulse*tangentDistance*invInertia;}else {this.m_velocityBuffer.data[particleIndex].SelfMulAdd(impulse*invMass,normal);}}}b2ParticleSystem.xTruncBits=12;b2ParticleSystem.yTruncBits=12;b2ParticleSystem.tagBits=8*4;b2ParticleSystem.yOffset=1<<b2ParticleSystem.yTruncBits-1;b2ParticleSystem.yShift=b2ParticleSystem.tagBits-b2ParticleSystem.yTruncBits;b2ParticleSystem.xShift=b2ParticleSystem.tagBits-b2ParticleSystem.yTruncBits-b2ParticleSystem.xTruncBits;b2ParticleSystem.xScale=1<<b2ParticleSystem.xShift;b2ParticleSystem.xOffset=b2ParticleSystem.xScale*(1<<b2ParticleSystem.xTruncBits-1);b2ParticleSystem.yMask=(1<<b2ParticleSystem.yTruncBits)-1<<b2ParticleSystem.yShift;b2ParticleSystem.xMask=~b2ParticleSystem.yMask;b2ParticleSystem.DestroyParticlesInShape_s_aabb=new b2AABB();b2ParticleSystem.CreateParticleGroup_s_transform=new b2Transform();b2ParticleSystem.ComputeCollisionEnergy_s_v=new b2Vec2();b2ParticleSystem.QueryShapeAABB_s_aabb=new b2AABB();b2ParticleSystem.QueryPointAABB_s_aabb=new b2AABB();b2ParticleSystem.RayCast_s_aabb=new b2AABB();b2ParticleSystem.RayCast_s_p=new b2Vec2();b2ParticleSystem.RayCast_s_v=new b2Vec2();b2ParticleSystem.RayCast_s_n=new b2Vec2();b2ParticleSystem.RayCast_s_point=new b2Vec2();b2ParticleSystem.k_pairFlags=exports.b2ParticleFlag.b2_springParticle;b2ParticleSystem.k_triadFlags=exports.b2ParticleFlag.b2_elasticParticle;b2ParticleSystem.k_noPressureFlags=exports.b2ParticleFlag.b2_powderParticle|exports.b2ParticleFlag.b2_tensileParticle;b2ParticleSystem.k_extraDampingFlags=exports.b2ParticleFlag.b2_staticPressureParticle;b2ParticleSystem.k_barrierWallFlags=exports.b2ParticleFlag.b2_barrierParticle|exports.b2ParticleFlag.b2_wallParticle;b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge=new b2EdgeShape();b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d=new b2Vec2();b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p=new b2Vec2();b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb=new b2AABB();b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dab=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dbc=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dca=new b2Vec2();b2ParticleSystem.AddContact_s_d=new b2Vec2();b2ParticleSystem.UpdateBodyContacts_s_aabb=new b2AABB();b2ParticleSystem.Solve_s_subStep=new b2TimeStep();b2ParticleSystem.SolveCollision_s_aabb=new b2AABB();b2ParticleSystem.SolveGravity_s_gravity=new b2Vec2();b2ParticleSystem.SolveBarrier_s_aabb=new b2AABB();b2ParticleSystem.SolveBarrier_s_va=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vb=new b2Vec2();b2ParticleSystem.SolveBarrier_s_pba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vc=new b2Vec2();b2ParticleSystem.SolveBarrier_s_pca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_qba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_qca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_dv=new b2Vec2();b2ParticleSystem.SolveBarrier_s_f=new b2Vec2();b2ParticleSystem.SolvePressure_s_f=new b2Vec2();b2ParticleSystem.SolveDamping_s_v=new b2Vec2();b2ParticleSystem.SolveDamping_s_f=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_t0=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_t1=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_p=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_v=new b2Vec2();b2ParticleSystem.SolveExtraDamping_s_v=new b2Vec2();b2ParticleSystem.SolveExtraDamping_s_f=new b2Vec2();b2ParticleSystem.SolveRigid_s_position=new b2Vec2();b2ParticleSystem.SolveRigid_s_rotation=new b2Rot();b2ParticleSystem.SolveRigid_s_transform=new b2Transform();b2ParticleSystem.SolveRigid_s_velocityTransform=new b2Transform();b2ParticleSystem.SolveElastic_s_pa=new b2Vec2();b2ParticleSystem.SolveElastic_s_pb=new b2Vec2();b2ParticleSystem.SolveElastic_s_pc=new b2Vec2();b2ParticleSystem.SolveElastic_s_r=new b2Rot();b2ParticleSystem.SolveElastic_s_t0=new b2Vec2();b2ParticleSystem.SolveSpring_s_pa=new b2Vec2();b2ParticleSystem.SolveSpring_s_pb=new b2Vec2();b2ParticleSystem.SolveSpring_s_d=new b2Vec2();b2ParticleSystem.SolveSpring_s_f=new b2Vec2();b2ParticleSystem.SolveTensile_s_weightedNormal=new b2Vec2();b2ParticleSystem.SolveTensile_s_s=new b2Vec2();b2ParticleSystem.SolveTensile_s_f=new b2Vec2();b2ParticleSystem.SolveViscous_s_v=new b2Vec2();b2ParticleSystem.SolveViscous_s_f=new b2Vec2();b2ParticleSystem.SolveRepulsive_s_f=new b2Vec2();b2ParticleSystem.SolvePowder_s_f=new b2Vec2();b2ParticleSystem.SolveSolid_s_f=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_n=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal=new b2Vec2();class b2ParticleSystem_UserOverridableBuffer{constructor(){this._data=null;this.userSuppliedCapacity=0;}get data(){return this._data;}set data(value){this._data=value;}}class b2ParticleSystem_Proxy{constructor(){this.index=b2_invalidParticleIndex;this.tag=0;}static CompareProxyProxy(a,b){return a.tag<b.tag;}static CompareTagProxy(a,b){return a<b.tag;}static CompareProxyTag(a,b){return a.tag<b;}}class b2ParticleSystem_InsideBoundsEnumerator{constructor(system,lower,upper,first,last){this.m_system=system;this.m_xLower=(lower&b2ParticleSystem.xMask)>>>0;this.m_xUpper=(upper&b2ParticleSystem.xMask)>>>0;this.m_yLower=(lower&b2ParticleSystem.yMask)>>>0;this.m_yUpper=(upper&b2ParticleSystem.yMask)>>>0;this.m_first=first;this.m_last=last;}GetNext(){while(this.m_first<this.m_last){const xTag=(this.m_system.m_proxyBuffer.data[this.m_first].tag&b2ParticleSystem.xMask)>>>0;if(xTag>=this.m_xLower&&xTag<=this.m_xUpper){return this.m_system.m_proxyBuffer.data[this.m_first++].index;}this.m_first++;}return b2_invalidParticleIndex;}}class b2ParticleSystem_ParticleListNode{constructor(){this.next=null;this.count=0;this.index=0;}}class b2ParticleSystem_FixedSetAllocator{Allocate(itemSize,count){return count;}Clear(){}GetCount(){return 0;}Invalidate(itemIndex){}GetValidBuffer(){return [];}GetBuffer(){return [];}SetCount(count){}}class b2ParticleSystem_FixtureParticle{constructor(fixture,particle){this.second=b2_invalidParticleIndex;this.first=fixture;this.second=particle;}}class b2ParticleSystem_FixtureParticleSet extends b2ParticleSystem_FixedSetAllocator{Initialize(bodyContactBuffer,flagsBuffer){}Find(pair){return b2_invalidParticleIndex;}}class b2ParticleSystem_ParticlePair{constructor(particleA,particleB){this.first=b2_invalidParticleIndex;this.second=b2_invalidParticleIndex;this.first=particleA;this.second=particleB;}}class b2ParticlePairSet extends b2ParticleSystem_FixedSetAllocator{Initialize(contactBuffer,flagsBuffer){}Find(pair){return b2_invalidParticleIndex;}}class b2ParticleSystem_ConnectionFilter{IsNecessary(index){return true;}ShouldCreatePair(a,b){return true;}ShouldCreateTriad(a,b,c){return true;}}class b2ParticleSystem_DestroyParticlesInShapeCallback extends b2QueryCallback{constructor(system,shape,xf,callDestructionListener){super();this.m_callDestructionListener=false;this.m_destroyed=0;this.m_system=system;this.m_shape=shape;this.m_xf=xf;this.m_callDestructionListener=callDestructionListener;this.m_destroyed=0;}ReportFixture(fixture){return false;}ReportParticle(particleSystem,index){if(particleSystem!==this.m_system){return false;}if(this.m_shape.TestPoint(this.m_xf,this.m_system.m_positionBuffer.data[index])){this.m_system.DestroyParticle(index,this.m_callDestructionListener);this.m_destroyed++;}return true;}Destroyed(){return this.m_destroyed;}}class b2ParticleSystem_JoinParticleGroupsFilter extends b2ParticleSystem_ConnectionFilter{constructor(threshold){super();this.m_threshold=0;this.m_threshold=threshold;}ShouldCreatePair(a,b){return a<this.m_threshold&&this.m_threshold<=b||b<this.m_threshold&&this.m_threshold<=a;}ShouldCreateTriad(a,b,c){return (a<this.m_threshold||b<this.m_threshold||c<this.m_threshold)&&(this.m_threshold<=a||this.m_threshold<=b||this.m_threshold<=c);}}class b2ParticleSystem_CompositeShape extends b2Shape{constructor(shapes,shapeCount=shapes.length){super(exports.b2ShapeType.e_unknown,0);this.m_shapeCount=0;this.m_shapes=shapes;this.m_shapeCount=shapeCount;}Clone(){throw new Error();}GetChildCount(){return 1;}TestPoint(xf,p){for(let i=0;i<this.m_shapeCount;i++){if(this.m_shapes[i].TestPoint(xf,p)){return true;}}return false;}ComputeDistance(xf,p,normal,childIndex){return 0;}RayCast(output,input,xf,childIndex){return false;}ComputeAABB(aabb,xf,childIndex){const s_subaabb=new b2AABB();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;for(let i=0;i<this.m_shapeCount;i++){const childCount=this.m_shapes[i].GetChildCount();for(let j=0;j<childCount;j++){const subaabb=s_subaabb;this.m_shapes[i].ComputeAABB(subaabb,xf,j);aabb.Combine1(subaabb);}}}ComputeMass(massData,density){}SetupDistanceProxy(proxy,index){}ComputeSubmergedArea(normal,offset,xf,c){return 0;}Dump(log){}}class b2ParticleSystem_ReactiveFilter extends b2ParticleSystem_ConnectionFilter{constructor(flagsBuffer){super();this.m_flagsBuffer=flagsBuffer;}IsNecessary(index){return (this.m_flagsBuffer.data[index]&exports.b2ParticleFlag.b2_reactiveParticle)!==0;}}class b2ParticleSystem_UpdateBodyContactsCallback extends b2FixtureParticleQueryCallback{constructor(system,contactFilter=null){super(system);this.m_contactFilter=null;this.m_contactFilter=contactFilter;}ShouldCollideFixtureParticle(fixture,particleSystem,particleIndex){if(this.m_contactFilter){const flags=this.m_system.GetFlagsBuffer();if(flags[particleIndex]&exports.b2ParticleFlag.b2_fixtureContactFilterParticle){return this.m_contactFilter.ShouldCollideFixtureParticle(fixture,this.m_system,particleIndex);}}return true;}ReportFixtureAndParticle(fixture,childIndex,a){const s_n=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n;const s_rp=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp;const ap=this.m_system.m_positionBuffer.data[a];const n=s_n;const d=fixture.ComputeDistance(ap,n,childIndex);if(d<this.m_system.m_particleDiameter&&this.ShouldCollideFixtureParticle(fixture,this.m_system,a)){const b=fixture.GetBody();const bp=b.GetWorldCenter();const bm=b.GetMass();const bI=b.GetInertia()-bm*b.GetLocalCenter().LengthSquared();const invBm=bm>0?1/bm:0;const invBI=bI>0?1/bI:0;const invAm=this.m_system.m_flagsBuffer.data[a]&exports.b2ParticleFlag.b2_wallParticle?0:this.m_system.GetParticleInvMass();const rp=b2Vec2.SubVV(ap,bp,s_rp);const rpn=b2Vec2.CrossVV(rp,n);const invM=invAm+invBm+invBI*rpn*rpn;const contact=this.m_system.m_bodyContactBuffer.data[this.m_system.m_bodyContactBuffer.Append()];contact.index=a;contact.body=b;contact.fixture=fixture;contact.weight=1-d*this.m_system.m_inverseDiameter;contact.normal.Copy(n.SelfNeg());contact.mass=invM>0?1/invM:0;this.m_system.DetectStuckParticle(a);}}}b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n=new b2Vec2();b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp=new b2Vec2();class b2ParticleSystem_SolveCollisionCallback extends b2FixtureParticleQueryCallback{constructor(system,step){super(system);this.m_step=step;}ReportFixtureAndParticle(fixture,childIndex,a){const s_p1=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p1;const s_output=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_output;const s_input=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_input;const s_p=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p;const s_v=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_v;const s_f=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_f;const body=fixture.GetBody();const ap=this.m_system.m_positionBuffer.data[a];const av=this.m_system.m_velocityBuffer.data[a];const output=s_output;const input=s_input;if(this.m_system.m_iterationIndex===0){const p1=b2Transform.MulTXV(body.m_xf0,ap,s_p1);if(fixture.GetShape().GetType()===exports.b2ShapeType.e_circleShape){p1.SelfSub(body.GetLocalCenter());b2Rot.MulRV(body.m_xf0.q,p1,p1);b2Rot.MulTRV(body.m_xf.q,p1,p1);p1.SelfAdd(body.GetLocalCenter());}b2Transform.MulXV(body.m_xf,p1,input.p1);}else {input.p1.Copy(ap);}b2Vec2.AddVMulSV(ap,this.m_step.dt,av,input.p2);input.maxFraction=1;if(fixture.RayCast(output,input,childIndex)){const n=output.normal;const p=s_p;p.x=(1-output.fraction)*input.p1.x+output.fraction*input.p2.x+b2_linearSlop*n.x;p.y=(1-output.fraction)*input.p1.y+output.fraction*input.p2.y+b2_linearSlop*n.y;const v=s_v;v.x=this.m_step.inv_dt*(p.x-ap.x);v.y=this.m_step.inv_dt*(p.y-ap.y);this.m_system.m_velocityBuffer.data[a].Copy(v);const f=s_f;f.x=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.x-v.x);f.y=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.y-v.y);this.m_system.ParticleApplyForce(a,f);}}ReportParticle(system,index){return false;}}b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p1=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_output=new b2RayCastOutput();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_input=new b2RayCastInput();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_v=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_f=new b2Vec2();class b2World{constructor(gravity){this.m_newFixture=false;this.m_locked=false;this.m_clearForces=true;this.m_contactManager=new b2ContactManager();this.m_bodyList=null;this.m_jointList=null;this.m_particleSystemList=null;this.m_bodyCount=0;this.m_jointCount=0;this.m_gravity=new b2Vec2();this.m_allowSleep=true;this.m_destructionListener=null;this.m_debugDraw=null;this.m_inv_dt0=0;this.m_warmStarting=true;this.m_continuousPhysics=true;this.m_subStepping=false;this.m_stepComplete=true;this.m_profile=new b2Profile();this.m_island=new b2Island();this.s_stack=[];this.m_controllerList=null;this.m_controllerCount=0;this.m_gravity.Copy(gravity);}SetDestructionListener(listener){this.m_destructionListener=listener;}SetContactFilter(filter){this.m_contactManager.m_contactFilter=filter;}SetContactListener(listener){this.m_contactManager.m_contactListener=listener;}SetDebugDraw(debugDraw){this.m_debugDraw=debugDraw;}CreateBody(def={}){if(this.IsLocked()){throw new Error();}const b=new b2Body(def,this);b.m_prev=null;b.m_next=this.m_bodyList;if(this.m_bodyList){this.m_bodyList.m_prev=b;}this.m_bodyList=b;++this.m_bodyCount;return b;}DestroyBody(b){if(this.IsLocked()){throw new Error();}let je=b.m_jointList;while(je){const je0=je;je=je.next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeJoint(je0.joint);}this.DestroyJoint(je0.joint);b.m_jointList=je;}b.m_jointList=null;let coe=b.m_controllerList;while(coe){const coe0=coe;coe=coe.nextController;coe0.controller.RemoveBody(b);}let ce=b.m_contactList;while(ce){const ce0=ce;ce=ce.next;this.m_contactManager.Destroy(ce0.contact);}b.m_contactList=null;let f=b.m_fixtureList;while(f){const f0=f;f=f.m_next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeFixture(f0);}f0.DestroyProxies();f0.Reset();b.m_fixtureList=f;b.m_fixtureCount-=1;}b.m_fixtureList=null;b.m_fixtureCount=0;if(b.m_prev){b.m_prev.m_next=b.m_next;}if(b.m_next){b.m_next.m_prev=b.m_prev;}if(b===this.m_bodyList){this.m_bodyList=b.m_next;}--this.m_bodyCount;}static _Joint_Create(def){switch(def.type){case exports.b2JointType.e_distanceJoint:return new b2DistanceJoint(def);case exports.b2JointType.e_mouseJoint:return new b2MouseJoint(def);case exports.b2JointType.e_prismaticJoint:return new b2PrismaticJoint(def);case exports.b2JointType.e_revoluteJoint:return new b2RevoluteJoint(def);case exports.b2JointType.e_pulleyJoint:return new b2PulleyJoint(def);case exports.b2JointType.e_gearJoint:return new b2GearJoint(def);case exports.b2JointType.e_wheelJoint:return new b2WheelJoint(def);case exports.b2JointType.e_weldJoint:return new b2WeldJoint(def);case exports.b2JointType.e_frictionJoint:return new b2FrictionJoint(def);case exports.b2JointType.e_ropeJoint:return new b2RopeJoint(def);case exports.b2JointType.e_motorJoint:return new b2MotorJoint(def);case exports.b2JointType.e_areaJoint:return new b2AreaJoint(def);}throw new Error();}static _Joint_Destroy(joint){}CreateJoint(def){if(this.IsLocked()){throw new Error();}const j=b2World._Joint_Create(def);j.m_prev=null;j.m_next=this.m_jointList;if(this.m_jointList){this.m_jointList.m_prev=j;}this.m_jointList=j;++this.m_jointCount;j.m_edgeA.prev=null;j.m_edgeA.next=j.m_bodyA.m_jointList;if(j.m_bodyA.m_jointList){j.m_bodyA.m_jointList.prev=j.m_edgeA;}j.m_bodyA.m_jointList=j.m_edgeA;j.m_edgeB.prev=null;j.m_edgeB.next=j.m_bodyB.m_jointList;if(j.m_bodyB.m_jointList){j.m_bodyB.m_jointList.prev=j.m_edgeB;}j.m_bodyB.m_jointList=j.m_edgeB;const bodyA=j.m_bodyA;const bodyB=j.m_bodyB;const collideConnected=j.m_collideConnected;if(!collideConnected){let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}return j;}DestroyJoint(j){if(this.IsLocked()){throw new Error();}if(j.m_prev){j.m_prev.m_next=j.m_next;}if(j.m_next){j.m_next.m_prev=j.m_prev;}if(j===this.m_jointList){this.m_jointList=j.m_next;}const bodyA=j.m_bodyA;const bodyB=j.m_bodyB;const collideConnected=j.m_collideConnected;bodyA.SetAwake(true);bodyB.SetAwake(true);if(j.m_edgeA.prev){j.m_edgeA.prev.next=j.m_edgeA.next;}if(j.m_edgeA.next){j.m_edgeA.next.prev=j.m_edgeA.prev;}if(j.m_edgeA===bodyA.m_jointList){bodyA.m_jointList=j.m_edgeA.next;}j.m_edgeA.Reset();if(j.m_edgeB.prev){j.m_edgeB.prev.next=j.m_edgeB.next;}if(j.m_edgeB.next){j.m_edgeB.next.prev=j.m_edgeB.prev;}if(j.m_edgeB===bodyB.m_jointList){bodyB.m_jointList=j.m_edgeB.next;}j.m_edgeB.Reset();b2World._Joint_Destroy(j);--this.m_jointCount;if(!collideConnected){let edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}}CreateParticleSystem(def){if(this.IsLocked()){throw new Error();}const p=new b2ParticleSystem(def,this);p.m_prev=null;p.m_next=this.m_particleSystemList;if(this.m_particleSystemList){this.m_particleSystemList.m_prev=p;}this.m_particleSystemList=p;return p;}DestroyParticleSystem(p){if(this.IsLocked()){throw new Error();}if(p.m_prev){p.m_prev.m_next=p.m_next;}if(p.m_next){p.m_next.m_prev=p.m_prev;}if(p===this.m_particleSystemList){this.m_particleSystemList=p.m_next;}}CalculateReasonableParticleIterations(timeStep){if(this.m_particleSystemList===null){return 1;}function GetSmallestRadius(world){let smallestRadius=b2_maxFloat;for(let system=world.GetParticleSystemList();system!==null;system=system.m_next){smallestRadius=b2Min(smallestRadius,system.GetRadius());}return smallestRadius;}return b2CalculateParticleIterations(this.m_gravity.Length(),GetSmallestRadius(this),timeStep);}Step(dt,velocityIterations,positionIterations,particleIterations=this.CalculateReasonableParticleIterations(dt)){const stepTimer=b2World.Step_s_stepTimer.Reset();if(this.m_newFixture){this.m_contactManager.FindNewContacts();this.m_newFixture=false;}this.m_locked=true;const step=b2World.Step_s_step;step.dt=dt;step.velocityIterations=velocityIterations;step.positionIterations=positionIterations;step.particleIterations=particleIterations;if(dt>0){step.inv_dt=1/dt;}else {step.inv_dt=0;}step.dtRatio=this.m_inv_dt0*dt;step.warmStarting=this.m_warmStarting;const timer=b2World.Step_s_timer.Reset();this.m_contactManager.Collide();this.m_profile.collide=timer.GetMilliseconds();if(this.m_stepComplete&&step.dt>0){const timer=b2World.Step_s_timer.Reset();for(let p=this.m_particleSystemList;p;p=p.m_next){p.Solve(step);}this.Solve(step);this.m_profile.solve=timer.GetMilliseconds();}if(this.m_continuousPhysics&&step.dt>0){const timer=b2World.Step_s_timer.Reset();this.SolveTOI(step);this.m_profile.solveTOI=timer.GetMilliseconds();}if(step.dt>0){this.m_inv_dt0=step.inv_dt;}if(this.m_clearForces){this.ClearForces();}this.m_locked=false;this.m_profile.step=stepTimer.GetMilliseconds();}ClearForces(){for(let body=this.m_bodyList;body;body=body.m_next){body.m_force.SetZero();body.m_torque=0;}}DrawParticleSystem(system){if(this.m_debugDraw===null){return;}const particleCount=system.GetParticleCount();if(particleCount){const radius=system.GetRadius();const positionBuffer=system.GetPositionBuffer();if(system.m_colorBuffer.data){const colorBuffer=system.GetColorBuffer();this.m_debugDraw.DrawParticles(positionBuffer,radius,colorBuffer,particleCount);}else {this.m_debugDraw.DrawParticles(positionBuffer,radius,null,particleCount);}}}DrawDebugData(){if(this.m_debugDraw===null){return;}const flags=this.m_debugDraw.GetFlags();const color=b2World.DrawDebugData_s_color.SetRGB(0,0,0);if(flags&exports.b2DrawFlags.e_shapeBit){for(let b=this.m_bodyList;b;b=b.m_next){const xf=b.m_xf;this.m_debugDraw.PushTransform(xf);for(let f=b.GetFixtureList();f;f=f.m_next){if(!b.IsActive()){color.SetRGB(0.5,0.5,0.3);this.DrawShape(f,color);}else if(b.GetType()===exports.b2BodyType.b2_staticBody){color.SetRGB(0.5,0.9,0.5);this.DrawShape(f,color);}else if(b.GetType()===exports.b2BodyType.b2_kinematicBody){color.SetRGB(0.5,0.5,0.9);this.DrawShape(f,color);}else if(!b.IsAwake()){color.SetRGB(0.6,0.6,0.6);this.DrawShape(f,color);}else {color.SetRGB(0.9,0.7,0.7);this.DrawShape(f,color);}}this.m_debugDraw.PopTransform(xf);}}if(flags&exports.b2DrawFlags.e_particleBit){for(let p=this.m_particleSystemList;p;p=p.m_next){this.DrawParticleSystem(p);}}if(flags&exports.b2DrawFlags.e_jointBit){for(let j=this.m_jointList;j;j=j.m_next){this.DrawJoint(j);}}if(flags&exports.b2DrawFlags.e_aabbBit){color.SetRGB(0.9,0.3,0.9);const vs=b2World.DrawDebugData_s_vs;for(let b=this.m_bodyList;b;b=b.m_next){if(!b.IsActive()){continue;}for(let f=b.GetFixtureList();f;f=f.m_next){for(let i=0;i<f.m_proxyCount;++i){const proxy=f.m_proxies[i];const aabb=proxy.treeNode.aabb;vs[0].Set(aabb.lowerBound.x,aabb.lowerBound.y);vs[1].Set(aabb.upperBound.x,aabb.lowerBound.y);vs[2].Set(aabb.upperBound.x,aabb.upperBound.y);vs[3].Set(aabb.lowerBound.x,aabb.upperBound.y);this.m_debugDraw.DrawPolygon(vs,4,color);}}}}if(flags&exports.b2DrawFlags.e_centerOfMassBit){for(let b=this.m_bodyList;b;b=b.m_next){const xf=b2World.DrawDebugData_s_xf;xf.q.Copy(b.m_xf.q);xf.p.Copy(b.GetWorldCenter());this.m_debugDraw.DrawTransform(xf);}}if(flags&exports.b2DrawFlags.e_controllerBit){for(let c=this.m_controllerList;c;c=c.m_next){c.Draw(this.m_debugDraw);}}}QueryAABB(...args){if(args[0]instanceof b2QueryCallback){this._QueryAABB(args[0],args[1]);}else {this._QueryAABB(null,args[0],args[1]);}}_QueryAABB(callback,aabb,fn){this.m_contactManager.m_broadPhase.Query(aabb,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}}QueryAllAABB(aabb,out=[]){this.QueryAABB(aabb,fixture=>{out.push(fixture);return true;});return out;}QueryPointAABB(...args){if(args[0]instanceof b2QueryCallback){this._QueryPointAABB(args[0],args[1]);}else {this._QueryPointAABB(null,args[0],args[1]);}}_QueryPointAABB(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}}QueryAllPointAABB(point,out=[]){this.QueryPointAABB(point,fixture=>{out.push(fixture);return true;});return out;}QueryFixtureShape(...args){if(args[0]instanceof b2QueryCallback){this._QueryFixtureShape(args[0],args[1],args[2],args[3]);}else {this._QueryFixtureShape(null,args[0],args[1],args[2],args[3]);}}_QueryFixtureShape(callback,shape,index,transform,fn){const aabb=b2World.QueryFixtureShape_s_aabb;shape.ComputeAABB(aabb,transform,index);this.m_contactManager.m_broadPhase.Query(aabb,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(b2TestOverlapShape(shape,index,fixture.GetShape(),fixture_proxy.childIndex,transform,fixture.GetBody().GetTransform())){if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}}return true;});if(callback instanceof b2QueryCallback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}}QueryAllFixtureShape(shape,index,transform,out=[]){this.QueryFixtureShape(shape,index,transform,fixture=>{out.push(fixture);return true;});return out;}QueryFixturePoint(...args){if(args[0]instanceof b2QueryCallback){this._QueryFixturePoint(args[0],args[1]);}else {this._QueryFixturePoint(null,args[0],args[1]);}}_QueryFixturePoint(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,proxy=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;if(fixture.TestPoint(point)){if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}}return true;});if(callback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}}QueryAllFixturePoint(point,out=[]){this.QueryFixturePoint(point,fixture=>{out.push(fixture);return true;});return out;}RayCast(...args){if(args[0]instanceof b2RayCastCallback){this._RayCast(args[0],args[1],args[2]);}else {this._RayCast(null,args[0],args[1],args[2]);}}_RayCast(callback,point1,point2,fn){const input=b2World.RayCast_s_input;input.maxFraction=1;input.p1.Copy(point1);input.p2.Copy(point2);this.m_contactManager.m_broadPhase.RayCast(input,(input,proxy)=>{const fixture_proxy=proxy.userData;const fixture=fixture_proxy.fixture;const index=fixture_proxy.childIndex;const output=b2World.RayCast_s_output;const hit=fixture.RayCast(output,input,index);if(hit){const fraction=output.fraction;const point=b2World.RayCast_s_point;point.Set((1-fraction)*point1.x+fraction*point2.x,(1-fraction)*point1.y+fraction*point2.y);if(callback){return callback.ReportFixture(fixture,point,output.normal,fraction);}else if(fn){return fn(fixture,point,output.normal,fraction);}}return input.maxFraction;});if(callback){for(let p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.RayCast(callback,point1,point2);}}}}RayCastOne(point1,point2){let result=null;let min_fraction=1;this.RayCast(point1,point2,(fixture,point,normal,fraction)=>{if(fraction<min_fraction){min_fraction=fraction;result=fixture;}return min_fraction;});return result;}RayCastAll(point1,point2,out=[]){this.RayCast(point1,point2,(fixture,point,normal,fraction)=>{out.push(fixture);return 1;});return out;}GetBodyList(){return this.m_bodyList;}GetJointList(){return this.m_jointList;}GetParticleSystemList(){return this.m_particleSystemList;}GetContactList(){return this.m_contactManager.m_contactList;}SetAllowSleeping(flag){if(flag===this.m_allowSleep){return;}this.m_allowSleep=flag;if(!this.m_allowSleep){for(let b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}}GetAllowSleeping(){return this.m_allowSleep;}SetWarmStarting(flag){this.m_warmStarting=flag;}GetWarmStarting(){return this.m_warmStarting;}SetContinuousPhysics(flag){this.m_continuousPhysics=flag;}GetContinuousPhysics(){return this.m_continuousPhysics;}SetSubStepping(flag){this.m_subStepping=flag;}GetSubStepping(){return this.m_subStepping;}GetProxyCount(){return this.m_contactManager.m_broadPhase.GetProxyCount();}GetBodyCount(){return this.m_bodyCount;}GetJointCount(){return this.m_jointCount;}GetContactCount(){return this.m_contactManager.m_contactCount;}GetTreeHeight(){return this.m_contactManager.m_broadPhase.GetTreeHeight();}GetTreeBalance(){return this.m_contactManager.m_broadPhase.GetTreeBalance();}GetTreeQuality(){return this.m_contactManager.m_broadPhase.GetTreeQuality();}SetGravity(gravity,wake=true){if(!b2Vec2.IsEqualToV(this.m_gravity,gravity)){this.m_gravity.Copy(gravity);if(wake){for(let b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}}}GetGravity(){return this.m_gravity;}IsLocked(){return this.m_locked;}SetAutoClearForces(flag){this.m_clearForces=flag;}GetAutoClearForces(){return this.m_clearForces;}ShiftOrigin(newOrigin){if(this.IsLocked()){throw new Error();}for(let b=this.m_bodyList;b;b=b.m_next){b.m_xf.p.SelfSub(newOrigin);b.m_sweep.c0.SelfSub(newOrigin);b.m_sweep.c.SelfSub(newOrigin);}for(let j=this.m_jointList;j;j=j.m_next){j.ShiftOrigin(newOrigin);}this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);}GetContactManager(){return this.m_contactManager;}GetProfile(){return this.m_profile;}Dump(log){if(this.m_locked){return;}log("const g: b2Vec2 = new b2Vec2(%.15f, %.15f);\n",this.m_gravity.x,this.m_gravity.y);log("this.m_world.SetGravity(g);\n");log("const bodies: b2Body[] = [];\n");log("const joints: b2Joint[] = [];\n");let i=0;for(let b=this.m_bodyList;b;b=b.m_next){b.m_islandIndex=i;b.Dump(log);++i;}i=0;for(let j=this.m_jointList;j;j=j.m_next){j.m_index=i;++i;}for(let j=this.m_jointList;j;j=j.m_next){if(j.m_type===exports.b2JointType.e_gearJoint){continue;}log("{\n");j.Dump(log);log("}\n");}for(let j=this.m_jointList;j;j=j.m_next){if(j.m_type!==exports.b2JointType.e_gearJoint){continue;}log("{\n");j.Dump(log);log("}\n");}}DrawJoint(joint){if(this.m_debugDraw===null){return;}const bodyA=joint.GetBodyA();const bodyB=joint.GetBodyB();const xf1=bodyA.m_xf;const xf2=bodyB.m_xf;const x1=xf1.p;const x2=xf2.p;const p1=joint.GetAnchorA(b2World.DrawJoint_s_p1);const p2=joint.GetAnchorB(b2World.DrawJoint_s_p2);const color=b2World.DrawJoint_s_color.SetRGB(0.5,0.8,0.8);switch(joint.m_type){case exports.b2JointType.e_distanceJoint:this.m_debugDraw.DrawSegment(p1,p2,color);break;case exports.b2JointType.e_pulleyJoint:{const pulley=joint;const s1=pulley.GetGroundAnchorA();const s2=pulley.GetGroundAnchorB();this.m_debugDraw.DrawSegment(s1,p1,color);this.m_debugDraw.DrawSegment(s2,p2,color);this.m_debugDraw.DrawSegment(s1,s2,color);break;}case exports.b2JointType.e_mouseJoint:{const c=b2World.DrawJoint_s_c;c.Set(0.0,1.0,0.0);this.m_debugDraw.DrawPoint(p1,4.0,c);this.m_debugDraw.DrawPoint(p2,4.0,c);c.Set(0.8,0.8,0.8);this.m_debugDraw.DrawSegment(p1,p2,c);break;}default:this.m_debugDraw.DrawSegment(x1,p1,color);this.m_debugDraw.DrawSegment(p1,p2,color);this.m_debugDraw.DrawSegment(x2,p2,color);}}DrawShape(fixture,color){if(this.m_debugDraw===null){return;}const shape=fixture.GetShape();switch(shape.m_type){case exports.b2ShapeType.e_circleShape:{const circle=shape;const center=circle.m_p;const radius=circle.m_radius;const axis=b2Vec2.UNITX;this.m_debugDraw.DrawSolidCircle(center,radius,axis,color);break;}case exports.b2ShapeType.e_edgeShape:{const edge=shape;const v1=edge.m_vertex1;const v2=edge.m_vertex2;this.m_debugDraw.DrawSegment(v1,v2,color);break;}case exports.b2ShapeType.e_chainShape:{const chain=shape;const count=chain.m_count;const vertices=chain.m_vertices;const ghostColor=b2World.DrawShape_s_ghostColor.SetRGBA(0.75*color.r,0.75*color.g,0.75*color.b,color.a);let v1=vertices[0];this.m_debugDraw.DrawPoint(v1,4.0,color);if(chain.m_hasPrevVertex){const vp=chain.m_prevVertex;this.m_debugDraw.DrawSegment(vp,v1,ghostColor);this.m_debugDraw.DrawCircle(vp,0.1,ghostColor);}for(let i=1;i<count;++i){const v2=vertices[i];this.m_debugDraw.DrawSegment(v1,v2,color);this.m_debugDraw.DrawPoint(v2,4.0,color);v1=v2;}if(chain.m_hasNextVertex){const vn=chain.m_nextVertex;this.m_debugDraw.DrawSegment(vn,v1,ghostColor);this.m_debugDraw.DrawCircle(vn,0.1,ghostColor);}break;}case exports.b2ShapeType.e_polygonShape:{const poly=shape;const vertexCount=poly.m_count;const vertices=poly.m_vertices;this.m_debugDraw.DrawSolidPolygon(vertices,vertexCount,color);break;}}}Solve(step){for(let b=this.m_bodyList;b;b=b.m_next){b.m_xf0.Copy(b.m_xf);}for(let controller=this.m_controllerList;controller;controller=controller.m_next){controller.Step(step);}this.m_profile.solveInit=0;this.m_profile.solveVelocity=0;this.m_profile.solvePosition=0;const island=this.m_island;island.Initialize(this.m_bodyCount,this.m_contactManager.m_contactCount,this.m_jointCount,this.m_contactManager.m_contactListener);for(let b=this.m_bodyList;b;b=b.m_next){b.m_islandFlag=false;}for(let c=this.m_contactManager.m_contactList;c;c=c.m_next){c.m_islandFlag=false;}for(let j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false;}const stack=this.s_stack;for(let seed=this.m_bodyList;seed;seed=seed.m_next){if(seed.m_islandFlag){continue;}if(!seed.IsAwake()||!seed.IsActive()){continue;}if(seed.GetType()===exports.b2BodyType.b2_staticBody){continue;}island.Clear();let stackCount=0;stack[stackCount++]=seed;seed.m_islandFlag=true;while(stackCount>0){const b=stack[--stackCount];if(!b){throw new Error();}island.AddBody(b);b.m_awakeFlag=true;if(b.GetType()===exports.b2BodyType.b2_staticBody){continue;}for(let ce=b.m_contactList;ce;ce=ce.next){const contact=ce.contact;if(contact.m_islandFlag){continue;}if(!contact.IsEnabled()||!contact.IsTouching()){continue;}const sensorA=contact.m_fixtureA.m_isSensor;const sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}island.AddContact(contact);contact.m_islandFlag=true;const other=ce.other;if(other.m_islandFlag){continue;}stack[stackCount++]=other;other.m_islandFlag=true;}for(let je=b.m_jointList;je;je=je.next){if(je.joint.m_islandFlag){continue;}const other=je.other;if(!other.IsActive()){continue;}island.AddJoint(je.joint);je.joint.m_islandFlag=true;if(other.m_islandFlag){continue;}stack[stackCount++]=other;other.m_islandFlag=true;}}const profile=new b2Profile();island.Solve(profile,step,this.m_gravity,this.m_allowSleep);this.m_profile.solveInit+=profile.solveInit;this.m_profile.solveVelocity+=profile.solveVelocity;this.m_profile.solvePosition+=profile.solvePosition;for(let i=0;i<island.m_bodyCount;++i){const b=island.m_bodies[i];if(b.GetType()===exports.b2BodyType.b2_staticBody){b.m_islandFlag=false;}}}for(let i=0;i<stack.length;++i){if(!stack[i]){break;}stack[i]=null;}const timer=new b2Timer();for(let b=this.m_bodyList;b;b=b.m_next){if(!b.m_islandFlag){continue;}if(b.GetType()===exports.b2BodyType.b2_staticBody){continue;}b.SynchronizeFixtures();}this.m_contactManager.FindNewContacts();this.m_profile.broadphase=timer.GetMilliseconds();}SolveTOI(step){const island=this.m_island;island.Initialize(2*b2_maxTOIContacts,b2_maxTOIContacts,0,this.m_contactManager.m_contactListener);if(this.m_stepComplete){for(let b=this.m_bodyList;b;b=b.m_next){b.m_islandFlag=false;b.m_sweep.alpha0=0;}for(let c=this.m_contactManager.m_contactList;c;c=c.m_next){c.m_toiFlag=false;c.m_islandFlag=false;c.m_toiCount=0;c.m_toi=1;}}for(;;){let minContact=null;let minAlpha=1;for(let c=this.m_contactManager.m_contactList;c;c=c.m_next){if(!c.IsEnabled()){continue;}if(c.m_toiCount>b2_maxSubSteps){continue;}let alpha=1;if(c.m_toiFlag){alpha=c.m_toi;}else {const fA=c.GetFixtureA();const fB=c.GetFixtureB();if(fA.IsSensor()||fB.IsSensor()){continue;}const bA=fA.GetBody();const bB=fB.GetBody();const typeA=bA.m_type;const typeB=bB.m_type;const activeA=bA.IsAwake()&&typeA!==exports.b2BodyType.b2_staticBody;const activeB=bB.IsAwake()&&typeB!==exports.b2BodyType.b2_staticBody;if(!activeA&&!activeB){continue;}const collideA=bA.IsBullet()||typeA!==exports.b2BodyType.b2_dynamicBody;const collideB=bB.IsBullet()||typeB!==exports.b2BodyType.b2_dynamicBody;if(!collideA&&!collideB){continue;}let alpha0=bA.m_sweep.alpha0;if(bA.m_sweep.alpha0<bB.m_sweep.alpha0){alpha0=bB.m_sweep.alpha0;bA.m_sweep.Advance(alpha0);}else if(bB.m_sweep.alpha0<bA.m_sweep.alpha0){alpha0=bA.m_sweep.alpha0;bB.m_sweep.Advance(alpha0);}const indexA=c.GetChildIndexA();const indexB=c.GetChildIndexB();const input=b2World.SolveTOI_s_toi_input;input.proxyA.SetShape(fA.GetShape(),indexA);input.proxyB.SetShape(fB.GetShape(),indexB);input.sweepA.Copy(bA.m_sweep);input.sweepB.Copy(bB.m_sweep);input.tMax=1;const output=b2World.SolveTOI_s_toi_output;b2TimeOfImpact(output,input);const beta=output.t;if(output.state===exports.b2TOIOutputState.e_touching){alpha=b2Min(alpha0+(1-alpha0)*beta,1);}else {alpha=1;}c.m_toi=alpha;c.m_toiFlag=true;}if(alpha<minAlpha){minContact=c;minAlpha=alpha;}}if(minContact===null||1-10*b2_epsilon<minAlpha){this.m_stepComplete=true;break;}const fA=minContact.GetFixtureA();const fB=minContact.GetFixtureB();const bA=fA.GetBody();const bB=fB.GetBody();const backup1=b2World.SolveTOI_s_backup1.Copy(bA.m_sweep);const backup2=b2World.SolveTOI_s_backup2.Copy(bB.m_sweep);bA.Advance(minAlpha);bB.Advance(minAlpha);minContact.Update(this.m_contactManager.m_contactListener);minContact.m_toiFlag=false;++minContact.m_toiCount;if(!minContact.IsEnabled()||!minContact.IsTouching()){minContact.SetEnabled(false);bA.m_sweep.Copy(backup1);bB.m_sweep.Copy(backup2);bA.SynchronizeTransform();bB.SynchronizeTransform();continue;}bA.SetAwake(true);bB.SetAwake(true);island.Clear();island.AddBody(bA);island.AddBody(bB);island.AddContact(minContact);bA.m_islandFlag=true;bB.m_islandFlag=true;minContact.m_islandFlag=true;for(let i=0;i<2;++i){const body=i===0?bA:bB;if(body.m_type===exports.b2BodyType.b2_dynamicBody){for(let ce=body.m_contactList;ce;ce=ce.next){if(island.m_bodyCount===island.m_bodyCapacity){break;}if(island.m_contactCount===island.m_contactCapacity){break;}const contact=ce.contact;if(contact.m_islandFlag){continue;}const other=ce.other;if(other.m_type===exports.b2BodyType.b2_dynamicBody&&!body.IsBullet()&&!other.IsBullet()){continue;}const sensorA=contact.m_fixtureA.m_isSensor;const sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}const backup=b2World.SolveTOI_s_backup.Copy(other.m_sweep);if(!other.m_islandFlag){other.Advance(minAlpha);}contact.Update(this.m_contactManager.m_contactListener);if(!contact.IsEnabled()){other.m_sweep.Copy(backup);other.SynchronizeTransform();continue;}if(!contact.IsTouching()){other.m_sweep.Copy(backup);other.SynchronizeTransform();continue;}contact.m_islandFlag=true;island.AddContact(contact);if(other.m_islandFlag){continue;}other.m_islandFlag=true;if(other.m_type!==exports.b2BodyType.b2_staticBody){other.SetAwake(true);}island.AddBody(other);}}}const subStep=b2World.SolveTOI_s_subStep;subStep.dt=(1-minAlpha)*step.dt;subStep.inv_dt=1/subStep.dt;subStep.dtRatio=1;subStep.positionIterations=20;subStep.velocityIterations=step.velocityIterations;subStep.particleIterations=step.particleIterations;subStep.warmStarting=false;island.SolveTOI(subStep,bA.m_islandIndex,bB.m_islandIndex);for(let i=0;i<island.m_bodyCount;++i){const body=island.m_bodies[i];body.m_islandFlag=false;if(body.m_type!==exports.b2BodyType.b2_dynamicBody){continue;}body.SynchronizeFixtures();for(let ce=body.m_contactList;ce;ce=ce.next){ce.contact.m_toiFlag=false;ce.contact.m_islandFlag=false;}}this.m_contactManager.FindNewContacts();if(this.m_subStepping){this.m_stepComplete=false;break;}}}AddController(controller){controller.m_next=this.m_controllerList;controller.m_prev=null;if(this.m_controllerList){this.m_controllerList.m_prev=controller;}this.m_controllerList=controller;++this.m_controllerCount;return controller;}RemoveController(controller){if(controller.m_prev){controller.m_prev.m_next=controller.m_next;}if(controller.m_next){controller.m_next.m_prev=controller.m_prev;}if(this.m_controllerList===controller){this.m_controllerList=controller.m_next;}--this.m_controllerCount;controller.m_prev=null;controller.m_next=null;return controller;}}b2World.Step_s_step=new b2TimeStep();b2World.Step_s_stepTimer=new b2Timer();b2World.Step_s_timer=new b2Timer();b2World.DrawDebugData_s_color=new b2Color(0,0,0);b2World.DrawDebugData_s_vs=b2Vec2.MakeArray(4);b2World.DrawDebugData_s_xf=new b2Transform();b2World.QueryFixtureShape_s_aabb=new b2AABB();b2World.RayCast_s_input=new b2RayCastInput();b2World.RayCast_s_output=new b2RayCastOutput();b2World.RayCast_s_point=new b2Vec2();b2World.DrawJoint_s_p1=new b2Vec2();b2World.DrawJoint_s_p2=new b2Vec2();b2World.DrawJoint_s_color=new b2Color(0.5,0.8,0.8);b2World.DrawJoint_s_c=new b2Color();b2World.DrawShape_s_ghostColor=new b2Color();b2World.SolveTOI_s_subStep=new b2TimeStep();b2World.SolveTOI_s_backup=new b2Sweep();b2World.SolveTOI_s_backup1=new b2Sweep();b2World.SolveTOI_s_backup2=new b2Sweep();b2World.SolveTOI_s_toi_input=new b2TOIInput();b2World.SolveTOI_s_toi_output=new b2TOIOutput();class b2ControllerEdge{constructor(controller,body){this.prevBody=null;this.nextBody=null;this.prevController=null;this.nextController=null;this.controller=controller;this.body=body;}}class b2Controller{constructor(){this.m_bodyList=null;this.m_bodyCount=0;this.m_prev=null;this.m_next=null;}GetNext(){return this.m_next;}GetPrev(){return this.m_prev;}GetBodyList(){return this.m_bodyList;}AddBody(body){const edge=new b2ControllerEdge(this,body);edge.nextBody=this.m_bodyList;edge.prevBody=null;if(this.m_bodyList){this.m_bodyList.prevBody=edge;}this.m_bodyList=edge;++this.m_bodyCount;edge.nextController=body.m_controllerList;edge.prevController=null;if(body.m_controllerList){body.m_controllerList.prevController=edge;}body.m_controllerList=edge;++body.m_controllerCount;}RemoveBody(body){if(this.m_bodyCount<=0){throw new Error();}let edge=this.m_bodyList;while(edge&&edge.body!==body){edge=edge.nextBody;}if(edge===null){throw new Error();}if(edge.prevBody){edge.prevBody.nextBody=edge.nextBody;}if(edge.nextBody){edge.nextBody.prevBody=edge.prevBody;}if(this.m_bodyList===edge){this.m_bodyList=edge.nextBody;}--this.m_bodyCount;if(edge.nextController){edge.nextController.prevController=edge.prevController;}if(edge.prevController){edge.prevController.nextController=edge.nextController;}if(body.m_controllerList===edge){body.m_controllerList=edge.nextController;}--body.m_controllerCount;}Clear(){while(this.m_bodyList){this.RemoveBody(this.m_bodyList.body);}this.m_bodyCount=0;}}class b2BuoyancyController extends b2Controller{constructor(){super(...arguments);this.normal=new b2Vec2(0,1);this.offset=0;this.density=0;this.velocity=new b2Vec2(0,0);this.linearDrag=0;this.angularDrag=0;this.useDensity=false;this.useWorldGravity=true;this.gravity=new b2Vec2(0,0);}Step(step){if(!this.m_bodyList){return;}if(this.useWorldGravity){this.gravity.Copy(this.m_bodyList.body.GetWorld().GetGravity());}for(let i=this.m_bodyList;i;i=i.nextBody){const body=i.body;if(!body.IsAwake()){continue;}const areac=new b2Vec2();const massc=new b2Vec2();let area=0;let mass=0;for(let fixture=body.GetFixtureList();fixture;fixture=fixture.m_next){const sc=new b2Vec2();const sarea=fixture.GetShape().ComputeSubmergedArea(this.normal,this.offset,body.GetTransform(),sc);area+=sarea;areac.x+=sarea*sc.x;areac.y+=sarea*sc.y;let shapeDensity=0;if(this.useDensity){shapeDensity=fixture.GetDensity();}else {shapeDensity=1;}mass+=sarea*shapeDensity;massc.x+=sarea*sc.x*shapeDensity;massc.y+=sarea*sc.y*shapeDensity;}areac.x/=area;areac.y/=area;massc.x/=mass;massc.y/=mass;if(area<b2_epsilon){continue;}const buoyancyForce=this.gravity.Clone().SelfNeg();buoyancyForce.SelfMul(this.density*area);body.ApplyForce(buoyancyForce,massc);const dragForce=body.GetLinearVelocityFromWorldPoint(areac,new b2Vec2());dragForce.SelfSub(this.velocity);dragForce.SelfMul(-this.linearDrag*area);body.ApplyForce(dragForce,areac);body.ApplyTorque(-body.GetInertia()/body.GetMass()*area*body.GetAngularVelocity()*this.angularDrag);}}Draw(debugDraw){const r=100;const p1=new b2Vec2();const p2=new b2Vec2();p1.x=this.normal.x*this.offset+this.normal.y*r;p1.y=this.normal.y*this.offset-this.normal.x*r;p2.x=this.normal.x*this.offset-this.normal.y*r;p2.y=this.normal.y*this.offset+this.normal.x*r;const color=new b2Color(0,0,0.8);debugDraw.DrawSegment(p1,p2,color);}}class b2ConstantAccelController extends b2Controller{constructor(){super(...arguments);this.A=new b2Vec2(0,0);}Step(step){const dtA=b2Vec2.MulSV(step.dt,this.A,b2ConstantAccelController.Step_s_dtA);for(let i=this.m_bodyList;i;i=i.nextBody){const body=i.body;if(!body.IsAwake()){continue;}body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),dtA,b2Vec2.s_t0));}}Draw(draw){}}b2ConstantAccelController.Step_s_dtA=new b2Vec2();class b2ConstantForceController extends b2Controller{constructor(){super(...arguments);this.F=new b2Vec2(0,0);}Step(step){for(let i=this.m_bodyList;i;i=i.nextBody){const body=i.body;if(!body.IsAwake()){continue;}body.ApplyForce(this.F,body.GetWorldCenter());}}Draw(draw){}}class b2GravityController extends b2Controller{constructor(){super(...arguments);this.G=1;this.invSqr=true;}Step(step){if(this.invSqr){for(let i=this.m_bodyList;i;i=i.nextBody){const body1=i.body;const p1=body1.GetWorldCenter();const mass1=body1.GetMass();for(let j=this.m_bodyList;j&&j!==i;j=j.nextBody){const body2=j.body;const p2=body2.GetWorldCenter();const mass2=body2.GetMass();const dx=p2.x-p1.x;const dy=p2.y-p1.y;const r2=dx*dx+dy*dy;if(r2<b2_epsilon){continue;}const f=b2GravityController.Step_s_f.Set(dx,dy);f.SelfMul(this.G/r2/b2Sqrt(r2)*mass1*mass2);if(body1.IsAwake()){body1.ApplyForce(f,p1);}if(body2.IsAwake()){body2.ApplyForce(f.SelfMul(-1),p2);}}}}else {for(let i=this.m_bodyList;i;i=i.nextBody){const body1=i.body;const p1=body1.GetWorldCenter();const mass1=body1.GetMass();for(let j=this.m_bodyList;j&&j!==i;j=j.nextBody){const body2=j.body;const p2=body2.GetWorldCenter();const mass2=body2.GetMass();const dx=p2.x-p1.x;const dy=p2.y-p1.y;const r2=dx*dx+dy*dy;if(r2<b2_epsilon){continue;}const f=b2GravityController.Step_s_f.Set(dx,dy);f.SelfMul(this.G/r2*mass1*mass2);if(body1.IsAwake()){body1.ApplyForce(f,p1);}if(body2.IsAwake()){body2.ApplyForce(f.SelfMul(-1),p2);}}}}}Draw(draw){}}b2GravityController.Step_s_f=new b2Vec2();class b2TensorDampingController extends b2Controller{constructor(){super(...arguments);this.T=new b2Mat22();this.maxTimestep=0;}Step(step){let timestep=step.dt;if(timestep<=b2_epsilon){return;}if(timestep>this.maxTimestep&&this.maxTimestep>0){timestep=this.maxTimestep;}for(let i=this.m_bodyList;i;i=i.nextBody){const body=i.body;if(!body.IsAwake()){continue;}const damping=body.GetWorldVector(b2Mat22.MulMV(this.T,body.GetLocalVector(body.GetLinearVelocity(),b2Vec2.s_t0),b2Vec2.s_t1),b2TensorDampingController.Step_s_damping);body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),b2Vec2.MulSV(timestep,damping,b2Vec2.s_t0),b2Vec2.s_t1));}}Draw(draw){}SetAxisAligned(xDamping,yDamping){this.T.ex.x=-xDamping;this.T.ex.y=0;this.T.ey.x=0;this.T.ey.y=-yDamping;if(xDamping>0||yDamping>0){this.maxTimestep=1/b2Max(xDamping,yDamping);}else {this.maxTimestep=0;}}}b2TensorDampingController.Step_s_damping=new b2Vec2();class b2RopeDef{constructor(){this.vertices=[];this.count=0;this.masses=[];this.gravity=new b2Vec2(0,0);this.damping=0.1;this.k2=0.9;this.k3=0.1;}}class b2Rope{constructor(){this.m_count=0;this.m_ps=[];this.m_p0s=[];this.m_vs=[];this.m_ims=[];this.m_Ls=[];this.m_as=[];this.m_gravity=new b2Vec2();this.m_damping=0;this.m_k2=1;this.m_k3=0.1;}GetVertexCount(){return this.m_count;}GetVertices(){return this.m_ps;}Initialize(def){this.m_count=def.count;this.m_ps=b2Vec2.MakeArray(this.m_count);this.m_p0s=b2Vec2.MakeArray(this.m_count);this.m_vs=b2Vec2.MakeArray(this.m_count);this.m_ims=b2MakeNumberArray(this.m_count);for(let i=0;i<this.m_count;++i){this.m_ps[i].Copy(def.vertices[i]);this.m_p0s[i].Copy(def.vertices[i]);this.m_vs[i].SetZero();const m=def.masses[i];if(m>0){this.m_ims[i]=1/m;}else {this.m_ims[i]=0;}}const count2=this.m_count-1;const count3=this.m_count-2;this.m_Ls=b2MakeNumberArray(count2);this.m_as=b2MakeNumberArray(count3);for(let i=0;i<count2;++i){const p1=this.m_ps[i];const p2=this.m_ps[i+1];this.m_Ls[i]=b2Vec2.DistanceVV(p1,p2);}for(let i=0;i<count3;++i){const p1=this.m_ps[i];const p2=this.m_ps[i+1];const p3=this.m_ps[i+2];const d1=b2Vec2.SubVV(p2,p1,b2Vec2.s_t0);const d2=b2Vec2.SubVV(p3,p2,b2Vec2.s_t1);const a=b2Vec2.CrossVV(d1,d2);const b=b2Vec2.DotVV(d1,d2);this.m_as[i]=b2Atan2(a,b);}this.m_gravity.Copy(def.gravity);this.m_damping=def.damping;this.m_k2=def.k2;this.m_k3=def.k3;}Step(h,iterations){if(h===0){return;}const d=Math.exp(-h*this.m_damping);for(let i=0;i<this.m_count;++i){this.m_p0s[i].Copy(this.m_ps[i]);if(this.m_ims[i]>0){this.m_vs[i].SelfMulAdd(h,this.m_gravity);}this.m_vs[i].SelfMul(d);this.m_ps[i].SelfMulAdd(h,this.m_vs[i]);}for(let i=0;i<iterations;++i){this.SolveC2();this.SolveC3();this.SolveC2();}const inv_h=1/h;for(let i=0;i<this.m_count;++i){b2Vec2.MulSV(inv_h,b2Vec2.SubVV(this.m_ps[i],this.m_p0s[i],b2Vec2.s_t0),this.m_vs[i]);}}SolveC2(){const count2=this.m_count-1;for(let i=0;i<count2;++i){const p1=this.m_ps[i];const p2=this.m_ps[i+1];const d=b2Vec2.SubVV(p2,p1,b2Rope.s_d);const L=d.Normalize();const im1=this.m_ims[i];const im2=this.m_ims[i+1];if(im1+im2===0){continue;}const s1=im1/(im1+im2);const s2=im2/(im1+im2);p1.SelfMulSub(this.m_k2*s1*(this.m_Ls[i]-L),d);p2.SelfMulAdd(this.m_k2*s2*(this.m_Ls[i]-L),d);}}SetAngle(angle){const count3=this.m_count-2;for(let i=0;i<count3;++i){this.m_as[i]=angle;}}SolveC3(){const count3=this.m_count-2;for(let i=0;i<count3;++i){const p1=this.m_ps[i];const p2=this.m_ps[i+1];const p3=this.m_ps[i+2];const m1=this.m_ims[i];const m2=this.m_ims[i+1];const m3=this.m_ims[i+2];const d1=b2Vec2.SubVV(p2,p1,b2Rope.s_d1);const d2=b2Vec2.SubVV(p3,p2,b2Rope.s_d2);const L1sqr=d1.LengthSquared();const L2sqr=d2.LengthSquared();if(L1sqr*L2sqr===0){continue;}const a=b2Vec2.CrossVV(d1,d2);const b=b2Vec2.DotVV(d1,d2);let angle=b2Atan2(a,b);const Jd1=b2Vec2.MulSV(-1/L1sqr,d1.SelfSkew(),b2Rope.s_Jd1);const Jd2=b2Vec2.MulSV(1/L2sqr,d2.SelfSkew(),b2Rope.s_Jd2);const J1=b2Vec2.NegV(Jd1,b2Rope.s_J1);const J2=b2Vec2.SubVV(Jd1,Jd2,b2Rope.s_J2);const J3=Jd2;let mass=m1*b2Vec2.DotVV(J1,J1)+m2*b2Vec2.DotVV(J2,J2)+m3*b2Vec2.DotVV(J3,J3);if(mass===0){continue;}mass=1/mass;let C=angle-this.m_as[i];while(C>b2_pi){angle-=2*b2_pi;C=angle-this.m_as[i];}while(C<-b2_pi){angle+=2*b2_pi;C=angle-this.m_as[i];}const impulse=-this.m_k3*mass*C;p1.SelfMulAdd(m1*impulse,J1);p2.SelfMulAdd(m2*impulse,J2);p3.SelfMulAdd(m3*impulse,J3);}}Draw(draw){const c=new b2Color(0.4,0.5,0.7);for(let i=0;i<this.m_count-1;++i){draw.DrawSegment(this.m_ps[i],this.m_ps[i+1],c);}}}b2Rope.s_d=new b2Vec2();b2Rope.s_d1=new b2Vec2();b2Rope.s_d2=new b2Vec2();b2Rope.s_Jd1=new b2Vec2();b2Rope.s_Jd2=new b2Vec2();b2Rope.s_J1=new b2Vec2();b2Rope.s_J2=new b2Vec2();exports.b2AABB=b2AABB;exports.b2Abs=b2Abs;exports.b2Acos=b2Acos;exports.b2Alloc=b2Alloc;exports.b2AreaJoint=b2AreaJoint;exports.b2AreaJointDef=b2AreaJointDef;exports.b2Asin=b2Asin;exports.b2Assert=b2Assert;exports.b2Atan2=b2Atan2;exports.b2BlockAllocator=b2BlockAllocator;exports.b2Body=b2Body;exports.b2BodyDef=b2BodyDef;exports.b2BroadPhase=b2BroadPhase;exports.b2BuoyancyController=b2BuoyancyController;exports.b2CalculateParticleIterations=b2CalculateParticleIterations;exports.b2ChainAndCircleContact=b2ChainAndCircleContact;exports.b2ChainAndPolygonContact=b2ChainAndPolygonContact;exports.b2ChainShape=b2ChainShape;exports.b2CircleContact=b2CircleContact;exports.b2CircleShape=b2CircleShape;exports.b2Clamp=b2Clamp;exports.b2ClipSegmentToLine=b2ClipSegmentToLine;exports.b2ClipVertex=b2ClipVertex;exports.b2CollideCircles=b2CollideCircles;exports.b2CollideEdgeAndCircle=b2CollideEdgeAndCircle;exports.b2CollideEdgeAndPolygon=b2CollideEdgeAndPolygon;exports.b2CollidePolygonAndCircle=b2CollidePolygonAndCircle;exports.b2CollidePolygons=b2CollidePolygons;exports.b2Color=b2Color;exports.b2ConstantAccelController=b2ConstantAccelController;exports.b2ConstantForceController=b2ConstantForceController;exports.b2Contact=b2Contact;exports.b2ContactEdge=b2ContactEdge;exports.b2ContactFactory=b2ContactFactory;exports.b2ContactFeature=b2ContactFeature;exports.b2ContactFilter=b2ContactFilter;exports.b2ContactID=b2ContactID;exports.b2ContactImpulse=b2ContactImpulse;exports.b2ContactListener=b2ContactListener;exports.b2ContactManager=b2ContactManager;exports.b2ContactPositionConstraint=b2ContactPositionConstraint;exports.b2ContactRegister=b2ContactRegister;exports.b2ContactSolver=b2ContactSolver;exports.b2ContactSolverDef=b2ContactSolverDef;exports.b2ContactVelocityConstraint=b2ContactVelocityConstraint;exports.b2Controller=b2Controller;exports.b2ControllerEdge=b2ControllerEdge;exports.b2Cos=b2Cos;exports.b2Counter=b2Counter;exports.b2DegToRad=b2DegToRad;exports.b2DestructionListener=b2DestructionListener;exports.b2Distance=b2Distance;exports.b2DistanceInput=b2DistanceInput;exports.b2DistanceJoint=b2DistanceJoint;exports.b2DistanceJointDef=b2DistanceJointDef;exports.b2DistanceOutput=b2DistanceOutput;exports.b2DistanceProxy=b2DistanceProxy;exports.b2Draw=b2Draw;exports.b2DynamicTree=b2DynamicTree;exports.b2EdgeAndCircleContact=b2EdgeAndCircleContact;exports.b2EdgeAndPolygonContact=b2EdgeAndPolygonContact;exports.b2EdgeShape=b2EdgeShape;exports.b2Filter=b2Filter;exports.b2Fixture=b2Fixture;exports.b2FixtureDef=b2FixtureDef;exports.b2FixtureParticleQueryCallback=b2FixtureParticleQueryCallback;exports.b2FixtureProxy=b2FixtureProxy;exports.b2Free=b2Free;exports.b2FrictionJoint=b2FrictionJoint;exports.b2FrictionJointDef=b2FrictionJointDef;exports.b2GearJoint=b2GearJoint;exports.b2GearJointDef=b2GearJointDef;exports.b2GetPointStates=b2GetPointStates;exports.b2GravityController=b2GravityController;exports.b2GrowableBuffer=b2GrowableBuffer;exports.b2GrowableStack=b2GrowableStack;exports.b2InvSqrt=b2InvSqrt;exports.b2IsPowerOfTwo=b2IsPowerOfTwo;exports.b2IsValid=b2IsValid;exports.b2Island=b2Island;exports.b2Jacobian=b2Jacobian;exports.b2Joint=b2Joint;exports.b2JointDef=b2JointDef;exports.b2JointEdge=b2JointEdge;exports.b2Log=b2Log;exports.b2MakeArray=b2MakeArray;exports.b2MakeNullArray=b2MakeNullArray;exports.b2MakeNumberArray=b2MakeNumberArray;exports.b2Manifold=b2Manifold;exports.b2ManifoldPoint=b2ManifoldPoint;exports.b2MassData=b2MassData;exports.b2Mat22=b2Mat22;exports.b2Mat33=b2Mat33;exports.b2Max=b2Max;exports.b2Maybe=b2Maybe;exports.b2Min=b2Min;exports.b2MixFriction=b2MixFriction;exports.b2MixRestitution=b2MixRestitution;exports.b2MotorJoint=b2MotorJoint;exports.b2MotorJointDef=b2MotorJointDef;exports.b2MouseJoint=b2MouseJoint;exports.b2MouseJointDef=b2MouseJointDef;exports.b2NextPowerOfTwo=b2NextPowerOfTwo;exports.b2Pair=b2Pair;exports.b2PairLessThan=b2PairLessThan;exports.b2ParseInt=b2ParseInt;exports.b2ParseUInt=b2ParseUInt;exports.b2ParticleBodyContact=b2ParticleBodyContact;exports.b2ParticleContact=b2ParticleContact;exports.b2ParticleDef=b2ParticleDef;exports.b2ParticleGroup=b2ParticleGroup;exports.b2ParticleGroupDef=b2ParticleGroupDef;exports.b2ParticleHandle=b2ParticleHandle;exports.b2ParticlePair=b2ParticlePair;exports.b2ParticlePairSet=b2ParticlePairSet;exports.b2ParticleSystem=b2ParticleSystem;exports.b2ParticleSystemDef=b2ParticleSystemDef;exports.b2ParticleSystem_CompositeShape=b2ParticleSystem_CompositeShape;exports.b2ParticleSystem_ConnectionFilter=b2ParticleSystem_ConnectionFilter;exports.b2ParticleSystem_DestroyParticlesInShapeCallback=b2ParticleSystem_DestroyParticlesInShapeCallback;exports.b2ParticleSystem_FixedSetAllocator=b2ParticleSystem_FixedSetAllocator;exports.b2ParticleSystem_FixtureParticle=b2ParticleSystem_FixtureParticle;exports.b2ParticleSystem_FixtureParticleSet=b2ParticleSystem_FixtureParticleSet;exports.b2ParticleSystem_InsideBoundsEnumerator=b2ParticleSystem_InsideBoundsEnumerator;exports.b2ParticleSystem_JoinParticleGroupsFilter=b2ParticleSystem_JoinParticleGroupsFilter;exports.b2ParticleSystem_ParticleListNode=b2ParticleSystem_ParticleListNode;exports.b2ParticleSystem_ParticlePair=b2ParticleSystem_ParticlePair;exports.b2ParticleSystem_Proxy=b2ParticleSystem_Proxy;exports.b2ParticleSystem_ReactiveFilter=b2ParticleSystem_ReactiveFilter;exports.b2ParticleSystem_SolveCollisionCallback=b2ParticleSystem_SolveCollisionCallback;exports.b2ParticleSystem_UpdateBodyContactsCallback=b2ParticleSystem_UpdateBodyContactsCallback;exports.b2ParticleSystem_UserOverridableBuffer=b2ParticleSystem_UserOverridableBuffer;exports.b2ParticleTriad=b2ParticleTriad;exports.b2PolygonAndCircleContact=b2PolygonAndCircleContact;exports.b2PolygonContact=b2PolygonContact;exports.b2PolygonShape=b2PolygonShape;exports.b2Position=b2Position;exports.b2PositionSolverManifold=b2PositionSolverManifold;exports.b2Pow=b2Pow;exports.b2PrismaticJoint=b2PrismaticJoint;exports.b2PrismaticJointDef=b2PrismaticJointDef;exports.b2Profile=b2Profile;exports.b2PulleyJoint=b2PulleyJoint;exports.b2PulleyJointDef=b2PulleyJointDef;exports.b2QueryCallback=b2QueryCallback;exports.b2RadToDeg=b2RadToDeg;exports.b2Random=b2Random;exports.b2RandomRange=b2RandomRange;exports.b2RayCastCallback=b2RayCastCallback;exports.b2RayCastInput=b2RayCastInput;exports.b2RayCastOutput=b2RayCastOutput;exports.b2RevoluteJoint=b2RevoluteJoint;exports.b2RevoluteJointDef=b2RevoluteJointDef;exports.b2Rope=b2Rope;exports.b2RopeDef=b2RopeDef;exports.b2RopeJoint=b2RopeJoint;exports.b2RopeJointDef=b2RopeJointDef;exports.b2Rot=b2Rot;exports.b2SeparationFunction=b2SeparationFunction;exports.b2Shape=b2Shape;exports.b2ShapeCast=b2ShapeCast;exports.b2ShapeCastInput=b2ShapeCastInput;exports.b2ShapeCastOutput=b2ShapeCastOutput;exports.b2Simplex=b2Simplex;exports.b2SimplexCache=b2SimplexCache;exports.b2SimplexVertex=b2SimplexVertex;exports.b2Sin=b2Sin;exports.b2SolverData=b2SolverData;exports.b2Sq=b2Sq;exports.b2Sqrt=b2Sqrt;exports.b2StackAllocator=b2StackAllocator;exports.b2Swap=b2Swap;exports.b2Sweep=b2Sweep;exports.b2TOIInput=b2TOIInput;exports.b2TOIOutput=b2TOIOutput;exports.b2TensorDampingController=b2TensorDampingController;exports.b2TestOverlapAABB=b2TestOverlapAABB;exports.b2TestOverlapShape=b2TestOverlapShape;exports.b2TimeOfImpact=b2TimeOfImpact;exports.b2TimeStep=b2TimeStep;exports.b2Timer=b2Timer;exports.b2Transform=b2Transform;exports.b2TreeNode=b2TreeNode;exports.b2Vec2=b2Vec2;exports.b2Vec2_zero=b2Vec2_zero;exports.b2Vec3=b2Vec3;exports.b2Velocity=b2Velocity;exports.b2VelocityConstraintPoint=b2VelocityConstraintPoint;exports.b2Version=b2Version;exports.b2WeldJoint=b2WeldJoint;exports.b2WeldJointDef=b2WeldJointDef;exports.b2WheelJoint=b2WheelJoint;exports.b2WheelJointDef=b2WheelJointDef;exports.b2World=b2World;exports.b2WorldManifold=b2WorldManifold;exports.b2_180_over_pi=b2_180_over_pi;exports.b2_aabbExtension=b2_aabbExtension;exports.b2_aabbMultiplier=b2_aabbMultiplier;exports.b2_angularSleepTolerance=b2_angularSleepTolerance;exports.b2_angularSlop=b2_angularSlop;exports.b2_barrierCollisionTime=b2_barrierCollisionTime;exports.b2_baumgarte=b2_baumgarte;exports.b2_branch=b2_branch;exports.b2_commit=b2_commit;exports.b2_epsilon=b2_epsilon;exports.b2_epsilon_sq=b2_epsilon_sq;exports.b2_gjk_reset=b2_gjk_reset;exports.b2_invalidParticleIndex=b2_invalidParticleIndex;exports.b2_linearSleepTolerance=b2_linearSleepTolerance;exports.b2_linearSlop=b2_linearSlop;exports.b2_maxAngularCorrection=b2_maxAngularCorrection;exports.b2_maxFloat=b2_maxFloat;exports.b2_maxLinearCorrection=b2_maxLinearCorrection;exports.b2_maxManifoldPoints=b2_maxManifoldPoints;exports.b2_maxParticleForce=b2_maxParticleForce;exports.b2_maxParticleIndex=b2_maxParticleIndex;exports.b2_maxParticlePressure=b2_maxParticlePressure;exports.b2_maxPolygonVertices=b2_maxPolygonVertices;exports.b2_maxRotation=b2_maxRotation;exports.b2_maxRotationSquared=b2_maxRotationSquared;exports.b2_maxSubSteps=b2_maxSubSteps;exports.b2_maxTOIContacts=b2_maxTOIContacts;exports.b2_maxTranslation=b2_maxTranslation;exports.b2_maxTranslationSquared=b2_maxTranslationSquared;exports.b2_maxTriadDistance=b2_maxTriadDistance;exports.b2_maxTriadDistanceSquared=b2_maxTriadDistanceSquared;exports.b2_minParticleSystemBufferCapacity=b2_minParticleSystemBufferCapacity;exports.b2_minParticleWeight=b2_minParticleWeight;exports.b2_minPulleyLength=b2_minPulleyLength;exports.b2_particleStride=b2_particleStride;exports.b2_pi=b2_pi;exports.b2_pi_over_180=b2_pi_over_180;exports.b2_polygonRadius=b2_polygonRadius;exports.b2_timeToSleep=b2_timeToSleep;exports.b2_toiBaumgarte=b2_toiBaumgarte;exports.b2_toi_reset=b2_toi_reset;exports.b2_two_pi=b2_two_pi;exports.b2_velocityThreshold=b2_velocityThreshold;exports.b2_version=b2_version;exports.g_blockSolve=g_blockSolve;Object.defineProperty(exports,'__esModule',{value:true});});})(box2d_umd,box2d_umd.exports);var box2d_umdExports=box2d_umd.exports;getDefaultExportFromCjs(box2d_umdExports);

      const box2d=box2d_umdExports;let b2={};for(var key in box2d){if(key.indexOf('b2_')!==-1){continue;}let newKey=key.replace('b2','');b2[newKey]=box2d[key];}var box2d_1=b2;var b2$1 = getDefaultExportFromCjs(box2d_1);

      const ERigidBody2DType = exports("ERigidBody2DType", {
        "Static": 0,
        "Kinematic": 1,
        "Dynamic": 2,
        "Animated": 3
      });
      Enum(ERigidBody2DType);
      const ECollider2DType = exports("ECollider2DType", {
        "None": 0,
        "BOX": 1,
        "CIRCLE": 2,
        "POLYGON": 3
      });
      Enum(ECollider2DType);
      const EJoint2DType = exports("EJoint2DType", {
        "None": 0,
        "DISTANCE": 1,
        "SPRING": 2,
        "WHEEL": 3,
        "MOUSE": 4,
        "FIXED": 5,
        "SLIDER": 6,
        "RELATIVE": 7,
        "HINGE": 8
      });
      Enum(EJoint2DType);
      const PhysicsGroup2D = exports("PhysicsGroup2D", {
        "DEFAULT": 1
      });
      Enum(PhysicsGroup2D);
      const PhysicsGroup$1 = exports("PhysicsGroup", PhysicsGroup2D);
      const ERaycast2DType = exports("ERaycast2DType", {
        "Closest": 0,
        "Any": 1,
        "AllClosest": 2,
        "All": 3
      });
      const Contact2DType = exports("Contact2DType", {
        None: 'none-contact',
        BEGIN_CONTACT: 'begin-contact',
        END_CONTACT: 'end-contact',
        PRE_SOLVE: 'pre-solve',
        POST_SOLVE: 'post-solve'
      });
      const EPhysics2DDrawFlags = exports("EPhysics2DDrawFlags", {
        "None": 0,
        "Shape": 1,
        "Joint": 2,
        "Aabb": 4,
        "Pair": 8,
        "CenterOfMass": 16,
        "Particle": 32,
        "Controller": 64,
        "All": 63
      });
      const PHYSICS_2D_PTM_RATIO = exports("PHYSICS_2D_PTM_RATIO", 32);

      class PhysicsContactListener extends b2$1.ContactListener {
        constructor(...args) {
          super(...args);
          this._contactFixtures = [];
          this._BeginContact = null;
          this._EndContact = null;
          this._PreSolve = null;
          this._PostSolve = null;
        }
        setBeginContact(cb) {
          this._BeginContact = cb;
        }
        setEndContact(cb) {
          this._EndContact = cb;
        }
        setPreSolve(cb) {
          this._PreSolve = cb;
        }
        setPostSolve(cb) {
          this._PostSolve = cb;
        }
        BeginContact(contact) {
          if (!this._BeginContact) return;
          const fixtureA = contact.GetFixtureA();
          const fixtureB = contact.GetFixtureB();
          const fixtures = this._contactFixtures;
          contact._shouldReport = false;
          if (fixtures.indexOf(fixtureA) !== -1 || fixtures.indexOf(fixtureB) !== -1) {
            contact._shouldReport = true;
            this._BeginContact(contact);
          }
        }
        EndContact(contact) {
          if (this._EndContact && contact._shouldReport) {
            contact._shouldReport = false;
            this._EndContact(contact);
          }
        }
        PreSolve(contact, oldManifold) {
          if (this._PreSolve && contact._shouldReport) {
            this._PreSolve(contact, oldManifold);
          }
        }
        PostSolve(contact, impulse) {
          if (this._PostSolve && contact._shouldReport) {
            this._PostSolve(contact, impulse);
          }
        }
        registerContactFixture(fixture) {
          this._contactFixtures.push(fixture);
        }
        unregisterContactFixture(fixture) {
          remove(this._contactFixtures, fixture);
        }
      }

      class PhysicsAABBQueryCallback extends b2$1.QueryCallback {
        constructor(...args) {
          super(...args);
          this._point = new b2$1.Vec2();
          this._isPoint = false;
          this._fixtures = [];
        }
        init(point) {
          if (point) {
            this._isPoint = true;
            this._point.x = point.x;
            this._point.y = point.y;
          } else {
            this._isPoint = false;
          }
          this._fixtures.length = 0;
        }
        ReportFixture(fixture) {
          if (this._isPoint) {
            if (fixture.TestPoint(this._point)) {
              this._fixtures.push(fixture);
            }
          } else {
            this._fixtures.push(fixture);
          }
          return true;
        }
        getFixture() {
          return this._fixtures[0];
        }
        getFixtures() {
          return this._fixtures;
        }
      }

      class PhysicsRayCastCallback extends b2$1.RayCastCallback {
        constructor(...args) {
          super(...args);
          this._type = 0;
          this._fixtures = [];
          this._points = [];
          this._normals = [];
          this._fractions = [];
          this._mask = 0xffffffff;
        }
        init(type, mask) {
          this._type = type;
          this._mask = mask;
          this._fixtures.length = 0;
          this._points.length = 0;
          this._normals.length = 0;
          this._fractions.length = 0;
        }
        ReportFixture(fixture, point, normal, fraction) {
          if ((fixture.GetFilterData().categoryBits & this._mask) === 0) {
            return -1;
          }
          if (this._type === 0) {
            this._fixtures[0] = fixture;
            this._points[0] = point;
            this._normals[0] = normal;
            this._fractions[0] = fraction;
            return fraction;
          }
          this._fixtures.push(fixture);
          this._points.push(new Vec2(point.x, point.y));
          this._normals.push(new Vec2(normal.x, normal.y));
          this._fractions.push(fraction);
          if (this._type === 1) {
            return 0;
          } else if (this._type >= 3) {
            return 1;
          }
          return fraction;
        }
        getFixtures() {
          return this._fixtures;
        }
        getPoints() {
          return this._points;
        }
        getNormals() {
          return this._normals;
        }
        getFractions() {
          return this._fractions;
        }
      }

      function At(i, vertices) {
        const s = vertices.length;
        return vertices[i < 0 ? s - -i % s : i % s];
      }
      function Copy(i, j, vertices) {
        const p = [];
        while (j < i) j += vertices.length;
        for (; i <= j; ++i) {
          p.push(At(i, vertices));
        }
        return p;
      }
      function ConvexPartition$1(vertices) {
        ForceCounterClockWise$1(vertices);
        let list = [];
        let d;
        let lowerDist;
        let upperDist;
        let p;
        let lowerInt = new Vec2();
        let upperInt = new Vec2();
        let lowerIndex = 0;
        let upperIndex = 0;
        let lowerPoly;
        let upperPoly;
        for (let i = 0; i < vertices.length; ++i) {
          if (Reflex(i, vertices)) {
            lowerDist = upperDist = 10e7;
            for (let j = 0; j < vertices.length; ++j) {
              if (Left(At(i - 1, vertices), At(i, vertices), At(j, vertices)) && RightOn(At(i - 1, vertices), At(i, vertices), At(j - 1, vertices))) {
                p = LineIntersect(At(i - 1, vertices), At(i, vertices), At(j, vertices), At(j - 1, vertices));
                if (Right(At(i + 1, vertices), At(i, vertices), p)) {
                  d = SquareDist(At(i, vertices), p);
                  if (d < lowerDist) {
                    lowerDist = d;
                    lowerInt = p;
                    lowerIndex = j;
                  }
                }
              }
              if (Left(At(i + 1, vertices), At(i, vertices), At(j + 1, vertices)) && RightOn(At(i + 1, vertices), At(i, vertices), At(j, vertices))) {
                p = LineIntersect(At(i + 1, vertices), At(i, vertices), At(j, vertices), At(j + 1, vertices));
                if (Left(At(i - 1, vertices), At(i, vertices), p)) {
                  d = SquareDist(At(i, vertices), p);
                  if (d < upperDist) {
                    upperDist = d;
                    upperIndex = j;
                    upperInt = p;
                  }
                }
              }
            }
            if (lowerIndex == (upperIndex + 1) % vertices.length) {
              const sp = lowerInt.add(upperInt).multiplyScalar(1 / 2);
              lowerPoly = Copy(i, upperIndex, vertices);
              lowerPoly.push(sp);
              upperPoly = Copy(lowerIndex, i, vertices);
              upperPoly.push(sp);
            } else {
              let highestScore = 0;
              let bestIndex = lowerIndex;
              while (upperIndex < lowerIndex) {
                upperIndex += vertices.length;
              }
              for (let j = lowerIndex; j <= upperIndex; ++j) {
                if (CanSee(i, j, vertices)) {
                  let score = 1 / (SquareDist(At(i, vertices), At(j, vertices)) + 1);
                  if (Reflex(j, vertices)) {
                    if (RightOn(At(j - 1, vertices), At(j, vertices), At(i, vertices)) && LeftOn(At(j + 1, vertices), At(j, vertices), At(i, vertices))) {
                      score += 3;
                    } else {
                      score += 2;
                    }
                  } else {
                    score += 1;
                  }
                  if (score > highestScore) {
                    bestIndex = j;
                    highestScore = score;
                  }
                }
              }
              lowerPoly = Copy(i, bestIndex, vertices);
              upperPoly = Copy(bestIndex, i, vertices);
            }
            list = list.concat(ConvexPartition$1(lowerPoly));
            list = list.concat(ConvexPartition$1(upperPoly));
            return list;
          }
        }
        list.push(vertices);
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].length == 0) list.splice(i, 0);
        }
        return list;
      }
      function CanSee(i, j, vertices) {
        if (Reflex(i, vertices)) {
          if (LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices)) && RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices))) return false;
        } else if (RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices)) || LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices))) return false;
        if (Reflex(j, vertices)) {
          if (LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices)) && RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices))) return false;
        } else if (RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices)) || LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices))) return false;
        for (let k = 0; k < vertices.length; ++k) {
          if ((k + 1) % vertices.length == i || k == i || (k + 1) % vertices.length == j || k == j) {
            continue;
          }
          const intersectionPoint = new Vec2();
          if (LineIntersect2(At(i, vertices), At(j, vertices), At(k, vertices), At(k + 1, vertices), intersectionPoint)) {
            return false;
          }
        }
        return true;
      }
      function Reflex(i, vertices) {
        return Right(i, vertices);
      }
      function Right(a, b, c) {
        if (typeof c === 'undefined') {
          const i = a;
          const vertices = b;
          a = At(i - 1, vertices);
          b = At(i, vertices);
          c = At(i + 1, vertices);
          if (typeof a === 'undefined') {
            a = b;
          }
          if (typeof c === 'undefined') {
            c = b;
          }
        }
        return Area(a, b, c) < 0;
      }
      function Left(a, b, c) {
        return Area(a, b, c) > 0;
      }
      function LeftOn(a, b, c) {
        return Area(a, b, c) >= 0;
      }
      function RightOn(a, b, c) {
        return Area(a, b, c) <= 0;
      }
      function SquareDist(a, b) {
        const dx = b.x - a.x;
        const dy = b.y - a.y;
        return dx * dx + dy * dy;
      }
      function ForceCounterClockWise$1(vertices) {
        if (!IsCounterClockWise(vertices)) {
          vertices.reverse();
        }
      }
      function IsCounterClockWise(vertices) {
        if (vertices.length < 3) return true;
        return GetSignedArea(vertices) > 0;
      }
      function GetSignedArea(vertices) {
        let i;
        let area = 0;
        for (i = 0; i < vertices.length; i++) {
          const j = (i + 1) % vertices.length;
          area += vertices[i].x * vertices[j].y;
          area -= vertices[i].y * vertices[j].x;
        }
        area /= 2;
        return area;
      }
      function LineIntersect(p1, p2, q1, q2) {
        const i = new Vec2();
        const a1 = p2.y - p1.y;
        const b1 = p1.x - p2.x;
        const c1 = a1 * p1.x + b1 * p1.y;
        const a2 = q2.y - q1.y;
        const b2 = q1.x - q2.x;
        const c2 = a2 * q1.x + b2 * q1.y;
        const det = a1 * b2 - a2 * b1;
        if (!FloatEquals(det, 0)) {
          i.x = (b2 * c1 - b1 * c2) / det;
          i.y = (a1 * c2 - a2 * c1) / det;
        }
        return i;
      }
      function LineIntersect2(a0, a1, b0, b1, intersectionPoint) {
        if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1) return false;
        const x1 = a0.x;
        const y1 = a0.y;
        const x2 = a1.x;
        const y2 = a1.y;
        const x3 = b0.x;
        const y3 = b0.y;
        const x4 = b1.x;
        const y4 = b1.y;
        if (Math.max(x1, x2) < Math.min(x3, x4) || Math.max(x3, x4) < Math.min(x1, x2)) return false;
        if (Math.max(y1, y2) < Math.min(y3, y4) || Math.max(y3, y4) < Math.min(y1, y2)) return false;
        let ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
        let ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
        const denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
        if (Math.abs(denom) < 10e-7) {
          return false;
        }
        ua /= denom;
        ub /= denom;
        if (ua > 0 && ua < 1 && ub > 0 && ub < 1) {
          intersectionPoint.x = x1 + ua * (x2 - x1);
          intersectionPoint.y = y1 + ua * (y2 - y1);
          return true;
        }
        return false;
      }
      function FloatEquals(value1, value2) {
        return Math.abs(value1 - value2) <= 10e-7;
      }
      function Area(a, b, c) {
        return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y);
      }

      var PolygonSeparator = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ConvexPartition: ConvexPartition$1,
        ForceCounterClockWise: ForceCounterClockWise$1,
        IsCounterClockWise: IsCounterClockWise
      });

      function ConvexPartition(polygon) {
        ForceCounterClockWise(polygon);
        let convex = true;
        for (let i = 0, len = polygon.length; i < len; ++i) {
          if (!isConvex(polygon[(i + len - 1) % len], polygon[i], polygon[(i + 1) % len])) {
            convex = false;
            break;
          }
        }
        if (convex) {
          return [polygon];
        }
        const ret = [];
        const triangles = Triangulate(polygon);
        if (!triangles) return null;
        for (; triangles.length;) {
          let poly = triangles.splice(0, 1)[0];
          for (let iPoly = 0, polyLen = poly.length; iPoly < polyLen; ++iPoly) {
            const diag1 = poly[iPoly];
            const diag2 = poly[(iPoly + 1) % polyLen];
            let tri3 = null;
            let iTri2 = 0;
            for (; iTri2 < triangles.length; ++iTri2) {
              const triangle = triangles[iTri2];
              for (let i = 0; i < 3; ++i) {
                const tri1 = triangle[i];
                const tri2 = triangle[(i + 1) % 3];
                if (equals(diag1, tri2) && equals(diag2, tri1)) {
                  tri3 = triangle[(i + 2) % 3];
                  break;
                }
              }
              if (tri3) {
                break;
              }
            }
            if (!tri3) {
              continue;
            }
            if (area(poly[(iPoly + polyLen - 1) % polyLen], diag1, tri3) > 0) {
              continue;
            }
            if (area(tri3, diag2, poly[(iPoly + 2) % polyLen]) > 0) {
              continue;
            }
            const newPoly = [];
            for (let i = (iPoly + 1) % polyLen; i !== iPoly; i = (i + 1) % polyLen) {
              newPoly.push(poly[i]);
            }
            newPoly.push(diag1, tri3);
            poly = newPoly;
            polyLen = newPoly.length;
            iPoly = -1;
            triangles.splice(iTri2, 1);
          }
          ret.push(poly);
        }
        return ret;
      }
      class Vertex {
        constructor() {
          this.isActive = false;
          this.isConvex = false;
          this.isEar = false;
          this.point = null;
          this.angleCos = 0;
          this.shouldUpdate = false;
          this.index = 0;
          this.prev = null;
          this.next = null;
        }
      }
      function area(a, b, c) {
        return (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);
      }
      function isConvex(p1, p2, p3) {
        return area(p1, p2, p3) < 0;
      }
      function equals(a, b) {
        return a.x === b.x && a.y === b.y;
      }
      function isClockwise(polygon) {
        let sum = 0;
        for (let i = 0, len = polygon.length; i < len; ++i) {
          const p1 = polygon[i];
          const p2 = polygon[(i + 1) % len];
          sum += (p2.x - p1.x) * (p2.y + p1.y);
        }
        return sum > 0;
      }
      function ForceCounterClockWise(vertices) {
        if (isClockwise(vertices)) {
          vertices.reverse();
        }
      }
      function updateVertex(vertex, vertices) {
        if (!vertex.shouldUpdate) {
          return;
        }
        vertex.shouldUpdate = false;
        const v1 = vertex.prev.point;
        const v2 = vertex.point;
        const v3 = vertex.next.point;
        vertex.isConvex = isConvex(v1, v2, v3);
        let v1x = v1.x - v2.x;
        let v1y = v1.y - v2.y;
        const v1Len = Math.sqrt(v1x * v1x + v1y * v1y);
        v1x /= v1Len;
        v1y /= v1Len;
        let v3x = v3.x - v2.x;
        let v3y = v3.y - v2.y;
        const v3Len = Math.sqrt(v3x * v3x + v3y * v3y);
        v3x /= v3Len;
        v3y /= v3Len;
        vertex.angleCos = v1x * v3x + v1y * v3y;
        if (vertex.isConvex) {
          vertex.isEar = true;
          for (let i = 0, len = vertices.length; i < len; ++i) {
            const curr = vertices[i];
            if (!curr.isActive || curr === vertex) {
              continue;
            }
            const currentPoint = curr.point;
            if (equals(v1, currentPoint) || equals(v2, currentPoint) || equals(v3, currentPoint)) {
              continue;
            }
            const areaA = area(v1, currentPoint, v2);
            const areaB = area(v2, currentPoint, v3);
            const areaC = area(v3, currentPoint, v1);
            if (areaA > 0 && areaB > 0 && areaC > 0) {
              vertex.isEar = false;
              break;
            }
            if (areaA === 0 && areaB >= 0 && areaC >= 0) {
              if (area(v1, curr.prev.point, v2) > 0 || area(v1, curr.next.point, v2) > 0) {
                vertex.isEar = false;
                break;
              }
            }
            if (areaB === 0 && areaA >= 0 && areaC >= 0) {
              if (area(v2, curr.prev.point, v3) > 0 || area(v2, curr.next.point, v3) > 0) {
                vertex.isEar = false;
                break;
              }
            }
            if (areaC === 0 && areaA >= 0 && areaB >= 0) {
              if (area(v3, curr.prev.point, v1) > 0 || area(v3, curr.next.point, v1) > 0) {
                vertex.isEar = false;
                break;
              }
            }
          }
        } else {
          vertex.isEar = false;
        }
      }
      function removeCollinearOrDuplicate(start) {
        for (let curr = start, end = start;;) {
          if (equals(curr.point, curr.next.point) || area(curr.prev.point, curr.point, curr.next.point) === 0) {
            curr.prev.next = curr.next;
            curr.next.prev = curr.prev;
            curr.prev.shouldUpdate = true;
            curr.next.shouldUpdate = true;
            if (curr === curr.next) {
              break;
            }
            end = curr.prev;
            curr = curr.next;
            continue;
          }
          curr = curr.next;
          if (curr === end) {
            break;
          }
        }
      }
      function Triangulate(polygon) {
        ForceCounterClockWise(polygon);
        if (polygon.length < 4) {
          return [polygon];
        }
        const len = polygon.length;
        const vertices = [];
        const triangles = [];
        for (let i = 0; i < len; ++i) {
          const v = new Vertex();
          v.isActive = true;
          v.isConvex = false;
          v.isEar = false;
          v.point = polygon[i];
          v.angleCos = 0;
          v.shouldUpdate = true;
          v.index = i;
          vertices.push(v);
        }
        for (let i = 0; i < len; ++i) {
          const vertex = vertices[i];
          vertex.prev = vertices[(i + len - 1) % len];
          vertex.next = vertices[(i + 1) % len];
        }
        vertices.forEach(vertex => updateVertex(vertex, vertices));
        for (let i = 0; i < len - 3; ++i) {
          let ear;
          for (let j = 0; j < len; ++j) {
            const vertex = vertices[j];
            if (!vertex.isActive || !vertex.isEar) {
              continue;
            }
            if (!ear) {
              ear = vertex;
            } else if (vertex.angleCos > ear.angleCos) {
              ear = vertex;
            }
          }
          if (!ear) {
            for (let i_1 = 0; i_1 < len; ++i_1) {
              const vertex = vertices[i_1];
              if (vertex.isActive) {
                const p1 = vertex.prev.point;
                const p2 = vertex.point;
                const p3 = vertex.next.point;
                if (Math.abs(area(p1, p2, p3)) > 1e-5) {
                  console.log('Failed to find ear. There might be self-intersection in the polygon.');
                  return null;
                }
              }
            }
            break;
          }
          triangles.push([ear.prev.point, ear.point, ear.next.point]);
          ear.isActive = false;
          ear.prev.next = ear.next;
          ear.next.prev = ear.prev;
          ear.prev.shouldUpdate = true;
          ear.next.shouldUpdate = true;
          removeCollinearOrDuplicate(ear.next);
          if (i === len - 4) {
            break;
          }
          for (let i_2 = 0; i_2 < len; ++i_2) {
            updateVertex(vertices[i_2], vertices);
          }
        }
        for (let i = 0; i < len; ++i) {
          const vertex = vertices[i];
          if (vertex.isActive) {
            vertex.prev.isActive = false;
            vertex.next.isActive = false;
            const p1 = vertex.prev.point;
            const p2 = vertex.point;
            const p3 = vertex.next.point;
            if (Math.abs(area(p1, p2, p3)) > 1e-5) {
              triangles.push([p1, p2, p3]);
            }
          }
        }
        return triangles;
      }

      var PolygonPartition = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ConvexPartition: ConvexPartition
      });

      class CollisionMatrix {
        constructor(strategy) {
          if (strategy === 1) {
            const self = this;
            for (let i = 0; i < 32; i++) {
              const key = `_${1 << i}`;
              self[key] = 0;
              self.updateArray = [];
              Object.defineProperty(self, 1 << i, {
                get() {
                  return this[key];
                },
                set(v) {
                  if (this[key] !== v) {
                    this[key] = v;
                    if (this.updateArray.indexOf(i) < 0) {
                      this.updateArray.push(i);
                    }
                  }
                }
              });
            }
            this['_1'] = 1;
          } else {
            for (let i = 0; i < 32; i++) {
              const key = 1 << i;
              this[`${key}`] = 0;
            }
            this['1'] = 1;
          }
        }
      }

      let instance = null;
      cclegacy.internal.PhysicsGroup2D = PhysicsGroup2D;
      class PhysicsSystem2D extends Eventify(System) {
        get enable() {
          return this._enable;
        }
        set enable(value) {
          this._enable = value;
        }
        get allowSleep() {
          return this._allowSleep;
        }
        set allowSleep(v) {
          this._allowSleep = v;
          {
            this.physicsWorld.setAllowSleep(v);
          }
        }
        get gravity() {
          return this._gravity;
        }
        set gravity(gravity) {
          this._gravity.set(gravity);
          {
            this.physicsWorld.setGravity(new Vec2(gravity.x / PHYSICS_2D_PTM_RATIO, gravity.y / PHYSICS_2D_PTM_RATIO));
          }
        }
        get maxSubSteps() {
          return this._maxSubSteps;
        }
        set maxSubSteps(value) {
          this._maxSubSteps = value;
        }
        get fixedTimeStep() {
          return this._fixedTimeStep;
        }
        set fixedTimeStep(value) {
          this._fixedTimeStep = value;
        }
        get autoSimulation() {
          return this._autoSimulation;
        }
        set autoSimulation(value) {
          this._autoSimulation = value;
        }
        get debugDrawFlags() {
          return this.physicsWorld.debugDrawFlags;
        }
        set debugDrawFlags(v) {
          this.physicsWorld.debugDrawFlags = v;
        }
        get physicsWorld() {
          return selector.physicsWorld;
        }
        static get PHYSICS_NONE() {
          return !selector.id;
        }
        static get PHYSICS_BUILTIN() {
          return selector.id === 'builtin';
        }
        static get PHYSICS_BOX2D() {
          return selector.id === 'box2d';
        }
        static get PHYSICS_BOX2D_WASM() {
          return selector.id === 'box2d-wasm';
        }
        static get PhysicsGroup() {
          return PhysicsGroup2D;
        }
        static get instance() {
          if (!instance) {
            instance = new PhysicsSystem2D();
          }
          return instance;
        }
        get stepping() {
          return this._steping;
        }
        constructor() {
          var _settings$querySettin, _settings$querySettin2, _settings$querySettin3, _settings$querySettin4;
          super();
          this.velocityIterations = 10;
          this.positionIterations = 10;
          this.collisionMatrix = new CollisionMatrix();
          this._enable = true;
          this._allowSleep = true;
          this._maxSubSteps = 1;
          this._fixedTimeStep = 1.0 / 60.0;
          this._autoSimulation = true;
          this._accumulator = 0;
          this._steping = false;
          this._gravity = new Vec2(0, -10 * PHYSICS_2D_PTM_RATIO);
          this._delayEvents = [];
          const gravity = settings.querySettings("physics", 'gravity');
          if (gravity) {
            Vec2.copy(this._gravity, gravity);
            this._gravity.multiplyScalar(PHYSICS_2D_PTM_RATIO);
          }
          this._allowSleep = (_settings$querySettin = settings.querySettings("physics", 'allowSleep')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : this._allowSleep;
          this._fixedTimeStep = (_settings$querySettin2 = settings.querySettings("physics", 'fixedTimeStep')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : this._fixedTimeStep;
          this._maxSubSteps = (_settings$querySettin3 = settings.querySettings("physics", 'maxSubSteps')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : this._maxSubSteps;
          this._autoSimulation = (_settings$querySettin4 = settings.querySettings("physics", 'autoSimulation')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : this._autoSimulation;
          const collisionMatrix = settings.querySettings("physics", 'collisionMatrix');
          if (collisionMatrix) {
            for (const i in collisionMatrix) {
              const bit = parseInt(i);
              const value = 1 << parseInt(i);
              this.collisionMatrix[`${value}`] = collisionMatrix[bit];
            }
          }
          const collisionGroups = settings.querySettings("physics", 'collisionGroups');
          if (collisionGroups) {
            const cg = collisionGroups;
            if (cg instanceof Array) {
              cg.forEach(v => {
                PhysicsGroup2D[v.name] = 1 << v.index;
              });
              Enum.update(PhysicsGroup2D);
            }
          }
          const mutableSelector = selector;
          mutableSelector.physicsWorld = createPhysicsWorld();
          this.gravity = this._gravity;
          this.allowSleep = this._allowSleep;
        }
        postUpdate(deltaTime) {
          if (!this._enable) {
            return;
          }
          if (!this._autoSimulation) {
            return;
          }
          director.emit("director_before_physics");
          this.physicsWorld.syncSceneToPhysics();
          this._steping = true;
          const fixedTimeStep = this._fixedTimeStep;
          const velocityIterations = this.velocityIterations;
          const positionIterations = this.positionIterations;
          this._accumulator += deltaTime;
          let substepIndex = 0;
          while (substepIndex++ < this._maxSubSteps && this._accumulator > fixedTimeStep) {
            this.physicsWorld.step(fixedTimeStep, velocityIterations, positionIterations);
            this._accumulator -= fixedTimeStep;
          }
          const events = this._delayEvents;
          for (let i = 0, l = events.length; i < l; i++) {
            const event = events[i];
            event.func.call(event.target);
          }
          events.length = 0;
          this.physicsWorld.syncPhysicsToScene();
          if (this.debugDrawFlags) {
            this.physicsWorld.drawDebug();
          }
          this._steping = false;
          director.emit("director_after_physics");
        }
        _callAfterStep(target, func) {
          if (this._steping) {
            this._delayEvents.push({
              target,
              func
            });
          } else {
            func.call(target);
          }
        }
        resetAccumulator(time = 0) {
          this._accumulator = time;
        }
        step(fixedTimeStep) {
          this.physicsWorld.step(fixedTimeStep, this.velocityIterations, this.positionIterations);
        }
        raycast(p1, p2, type = 0, mask = 0xffffffff) {
          return this.physicsWorld.raycast(p1, p2, type, mask);
        }
        testPoint(p) {
          return this.physicsWorld.testPoint(p);
        }
        testAABB(rect) {
          return this.physicsWorld.testAABB(rect);
        }
        static constructAndRegister() {
          director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW);
        }
      } exports("PhysicsSystem2D", PhysicsSystem2D);
      PhysicsSystem2D.ID = 'PHYSICS_2D';
      {
        director.once("director_init", () => {
          PhysicsSystem2D.constructAndRegister();
        });
      }

      const Physics2DManifoldType = exports("Physics2DManifoldType", {
        "Circles": 0,
        "FaceA": 1,
        "FaceB": 2
      });

      const ERigidBodyType = {
        "DYNAMIC": 1,
        "STATIC": 2,
        "KINEMATIC": 4
      };
      Enum(ERigidBodyType);
      const EAxisDirection = {
        "X_AXIS": 0,
        "Y_AXIS": 1,
        "Z_AXIS": 2
      };
      Enum(EAxisDirection);
      const ED6Axis = {
        "X": 0,
        "Y": 1,
        "Z": 2,
        "SWING1": 3,
        "SWING2": 4,
        "TWIST": 5
      };
      Enum(ED6Axis);
      const ESimplexType = {
        "VERTEX": 1,
        "LINE": 2,
        "TRIANGLE": 3,
        "TETRAHEDRON": 4
      };
      Enum(ESimplexType);
      const EColliderType = {
        "BOX": 0,
        "SPHERE": 1,
        "CAPSULE": 2,
        "CYLINDER": 3,
        "CONE": 4,
        "MESH": 5,
        "PLANE": 6,
        "SIMPLEX": 7,
        "TERRAIN": 8
      };
      Enum(EColliderType);
      const EConstraintType = {
        "POINT_TO_POINT": 0,
        "HINGE": 1,
        "FIXED": 2,
        "CONFIGURABLE": 3
      };
      Enum(EConstraintType);
      const EConstraintMode = {
        "FREE": 0,
        "LIMITED": 1,
        "LOCKED": 2
      };
      Enum(EConstraintMode);
      const EDriverMode = {
        "DISABLED": 0,
        "SERVO": 1,
        "INDUCTION": 2
      };
      Enum(EDriverMode);
      const ECharacterControllerType = {
        "BOX": 0,
        "CAPSULE": 1
      };
      Enum(ECharacterControllerType);
      const PhysicsGroup = {
        "DEFAULT": 1
      };
      Enum(PhysicsGroup);
      const EPhysicsDrawFlags = {
        "NONE": 0,
        "WIRE_FRAME": 1,
        "CONSTRAINT": 2,
        "AABB": 4
      };
      Enum(EPhysicsDrawFlags);

      var _dec$K, _dec2$G, _dec3$B, _dec4$r, _dec5$q, _dec6$j, _dec7$f, _dec8$a, _dec9$8, _dec10$3, _class$K, _class2$F, _initializer$E, _initializer2$A, _initializer3$s, _initializer4$p, _initializer5$k, _initializer6$g, _initializer7$d, _initializer8$c, _initializer9$a, _initializer10$9, _initializer11$9, _initializer12$8;
      const {
        type: type$3,
        menu: menu$c,
        ccclass: ccclass$e
      } = _decorator;
      let RigidBody2D = exports("RigidBody2D", (_dec$K = ccclass$e('cc.RigidBody2D'), _dec2$G = type$3(PhysicsGroup), _dec3$B = type$3(ERigidBody2DType), _dec4$r = type$3(CCBoolean), _dec5$q = type$3(CCFloat), _dec6$j = type$3(CCFloat), _dec7$f = type$3(CCFloat), _dec8$a = type$3(Vec2), _dec9$8 = type$3(CCFloat), _dec10$3 = type$3(CCBoolean), _dec$K(_class$K = (_class2$F = class RigidBody2D extends Component {
        constructor(...args) {
          super(...args);
          this.enabledContactListener = _initializer$E && _initializer$E();
          this.bullet = _initializer2$A && _initializer2$A();
          this.awakeOnLoad = _initializer3$s && _initializer3$s();
          this._body = null;
          this._group = _initializer4$p && _initializer4$p();
          this._type = _initializer5$k && _initializer5$k();
          this._allowSleep = _initializer6$g && _initializer6$g();
          this._gravityScale = _initializer7$d && _initializer7$d();
          this._linearDamping = _initializer8$c && _initializer8$c();
          this._angularDamping = _initializer9$a && _initializer9$a();
          this._linearVelocity = _initializer10$9 && _initializer10$9();
          this._angularVelocity = _initializer11$9 && _initializer11$9();
          this._fixedRotation = _initializer12$8 && _initializer12$8();
        }
        get group() {
          return this._group;
        }
        set group(v) {
          this._group = v;
        }
        get type() {
          return this._type;
        }
        set type(v) {
          this._type = v;
          if (this._body) {
            if (v === 3) {
              this._body.setType(1);
            } else {
              this._body.setType(v);
            }
          }
        }
        get allowSleep() {
          return this._allowSleep;
        }
        set allowSleep(v) {
          this._allowSleep = v;
          if (this._body) {
            this._body.setAllowSleep(v);
          }
        }
        get gravityScale() {
          return this._gravityScale;
        }
        set gravityScale(v) {
          this._gravityScale = v;
          if (this._body) {
            this._body.setGravityScale(v);
          }
        }
        get linearDamping() {
          return this._linearDamping;
        }
        set linearDamping(v) {
          this._linearDamping = v;
          if (this._body) {
            this._body.setLinearDamping(v);
          }
        }
        get angularDamping() {
          return this._angularDamping;
        }
        set angularDamping(v) {
          this._angularDamping = v;
          if (this._body) {
            this._body.setAngularDamping(v);
          }
        }
        get linearVelocity() {
          if (this._body) {
            this._body.getLinearVelocity(this._linearVelocity);
          }
          return this._linearVelocity;
        }
        set linearVelocity(v) {
          this._linearVelocity = v;
          if (this._body) {
            this._body.setLinearVelocity(v);
          }
        }
        get angularVelocity() {
          if (this._body) {
            this._angularVelocity = this._body.getAngularVelocity();
          }
          return this._angularVelocity;
        }
        set angularVelocity(v) {
          this._angularVelocity = v;
          if (this._body) {
            this._body.setAngularVelocity(v);
          }
        }
        get fixedRotation() {
          return this._fixedRotation;
        }
        set fixedRotation(v) {
          this._fixedRotation = v;
          if (this._body) {
            this._body.setFixedRotation(v);
          }
        }
        isAwake() {
          if (this._body) {
            return this._body.isAwake;
          }
          return false;
        }
        wakeUp() {
          if (this._body) {
            this._body.wakeUp();
          }
        }
        sleep() {
          if (this._body) {
            this._body.sleep();
          }
        }
        getMass() {
          if (this._body) {
            return this._body.getMass();
          }
          return 0;
        }
        applyForce(force, point, wake) {
          if (this._body) {
            this._body.applyForce(force, point, wake);
          }
        }
        applyForceToCenter(force, wake) {
          if (this._body) {
            this._body.applyForceToCenter(force, wake);
          }
        }
        applyTorque(torque, wake) {
          if (this._body) {
            this._body.applyTorque(torque, wake);
          }
        }
        applyLinearImpulse(impulse, point, wake) {
          if (this._body) {
            this._body.applyLinearImpulse(impulse, point, wake);
          }
        }
        applyLinearImpulseToCenter(impulse, wake) {
          if (this._body) {
            this._body.applyLinearImpulseToCenter(impulse, wake);
          }
        }
        applyAngularImpulse(impulse, wake) {
          if (this._body) {
            this._body.applyAngularImpulse(impulse, wake);
          }
        }
        getLinearVelocityFromWorldPoint(worldPoint, out) {
          if (this._body) {
            return this._body.getLinearVelocityFromWorldPoint(worldPoint, out);
          }
          return out;
        }
        getLocalVector(worldVector, out) {
          if (this._body) {
            return this._body.getLocalVector(worldVector, out);
          }
          return out;
        }
        getWorldVector(localVector, out) {
          if (this._body) {
            return this._body.getWorldVector(localVector, out);
          }
          return out;
        }
        getLocalPoint(worldPoint, out) {
          if (this._body) {
            return this._body.getLocalPoint(worldPoint, out);
          }
          return out;
        }
        getWorldPoint(localPoint, out) {
          if (this._body) {
            return this._body.getWorldPoint(localPoint, out);
          }
          return out;
        }
        getLocalCenter(out) {
          if (this._body) {
            return this._body.getLocalCenter(out);
          }
          return out;
        }
        getWorldCenter(out) {
          if (this._body) {
            return this._body.getWorldCenter(out);
          }
          return out;
        }
        getInertia() {
          if (this._body) {
            return this._body.getInertia();
          }
          return 0;
        }
        onLoad() {
          {
            this._body = createRigidBody();
            this._body.initialize(this);
          }
        }
        onEnable() {
          if (this._body) {
            this._body.onEnable();
          }
        }
        onDisable() {
          if (this._body) {
            this._body.onDisable();
          }
        }
        onDestroy() {
          if (this._body) {
            this._body.onDestroy();
          }
        }
        get impl() {
          return this._body;
        }
      }, (_applyDecoratedDescriptor(_class2$F.prototype, "group", [_dec2$G], Object.getOwnPropertyDescriptor(_class2$F.prototype, "group"), _class2$F.prototype), _initializer$E = applyDecoratedInitializer(_class2$F.prototype, "enabledContactListener", [serializable$l], function () {
        return false;
      }), _initializer2$A = applyDecoratedInitializer(_class2$F.prototype, "bullet", [serializable$l], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$F.prototype, "type", [_dec3$B], Object.getOwnPropertyDescriptor(_class2$F.prototype, "type"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "allowSleep", [_dec4$r], Object.getOwnPropertyDescriptor(_class2$F.prototype, "allowSleep"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "gravityScale", [_dec5$q], Object.getOwnPropertyDescriptor(_class2$F.prototype, "gravityScale"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "linearDamping", [_dec6$j], Object.getOwnPropertyDescriptor(_class2$F.prototype, "linearDamping"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "angularDamping", [_dec7$f], Object.getOwnPropertyDescriptor(_class2$F.prototype, "angularDamping"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "linearVelocity", [_dec8$a], Object.getOwnPropertyDescriptor(_class2$F.prototype, "linearVelocity"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "angularVelocity", [_dec9$8], Object.getOwnPropertyDescriptor(_class2$F.prototype, "angularVelocity"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "fixedRotation", [_dec10$3], Object.getOwnPropertyDescriptor(_class2$F.prototype, "fixedRotation"), _class2$F.prototype), _initializer3$s = applyDecoratedInitializer(_class2$F.prototype, "awakeOnLoad", [serializable$l], function () {
        return true;
      }), _initializer4$p = applyDecoratedInitializer(_class2$F.prototype, "_group", [serializable$l], function () {
        return 1;
      }), _initializer5$k = applyDecoratedInitializer(_class2$F.prototype, "_type", [serializable$l], function () {
        return 2;
      }), _initializer6$g = applyDecoratedInitializer(_class2$F.prototype, "_allowSleep", [serializable$l], function () {
        return true;
      }), _initializer7$d = applyDecoratedInitializer(_class2$F.prototype, "_gravityScale", [serializable$l], function () {
        return 1;
      }), _initializer8$c = applyDecoratedInitializer(_class2$F.prototype, "_linearDamping", [serializable$l], function () {
        return 0;
      }), _initializer9$a = applyDecoratedInitializer(_class2$F.prototype, "_angularDamping", [serializable$l], function () {
        return 0;
      }), _initializer10$9 = applyDecoratedInitializer(_class2$F.prototype, "_linearVelocity", [serializable$l], function () {
        return new Vec2();
      }), _initializer11$9 = applyDecoratedInitializer(_class2$F.prototype, "_angularVelocity", [serializable$l], function () {
        return 0;
      }), _initializer12$8 = applyDecoratedInitializer(_class2$F.prototype, "_fixedRotation", [serializable$l], function () {
        return false;
      })), _class2$F)) || _class$K));

      var _dec$J, _dec2$F, _dec3$A, _dec4$q, _dec5$p, _dec6$i, _dec7$e, _dec8$9, _class$J, _class2$E, _initializer$D, _initializer2$z, _initializer3$r, _initializer4$o, _initializer5$j, _initializer6$f, _initializer7$c;
      const {
        ccclass: ccclass$d,
        editable: editable$1,
        type: type$2
      } = _decorator;
      let Collider2D = exports("Collider2D", (_dec$J = ccclass$d('cc.Collider2D'), _dec2$F = type$2(CCFloat), _dec3$A = type$2(PhysicsGroup), _dec4$q = type$2(CCFloat), _dec5$p = type$2(CCBoolean), _dec6$i = type$2(CCFloat), _dec7$e = type$2(CCFloat), _dec8$9 = type$2(Vec2), _dec$J(_class$J = (_class2$E = class Collider2D extends Eventify(Component) {
        constructor(...args) {
          super(...args);
          this.editing = false;
          this.tag = _initializer$D && _initializer$D();
          this.TYPE = 0;
          this._shape = null;
          this._body = null;
          this._group = _initializer2$z && _initializer2$z();
          this._density = _initializer3$r && _initializer3$r();
          this._sensor = _initializer4$o && _initializer4$o();
          this._friction = _initializer5$j && _initializer5$j();
          this._restitution = _initializer6$f && _initializer6$f();
          this._offset = _initializer7$c && _initializer7$c();
        }
        get group() {
          return this._group;
        }
        set group(v) {
          this._group = v;
          if (this._shape && this._shape.onGroupChanged) {
            this._shape.onGroupChanged();
          }
        }
        get density() {
          return this._density;
        }
        set density(v) {
          this._density = v;
        }
        get sensor() {
          return this._sensor;
        }
        set sensor(v) {
          this._sensor = v;
        }
        get friction() {
          return this._friction;
        }
        set friction(v) {
          this._friction = v;
        }
        get restitution() {
          return this._restitution;
        }
        set restitution(v) {
          this._restitution = v;
        }
        get offset() {
          return this._offset;
        }
        set offset(v) {
          this._offset = v;
        }
        get body() {
          return this._body;
        }
        get impl() {
          return this._shape;
        }
        onLoad() {
          {
            this._shape = createShape(this.TYPE);
            this._shape.initialize(this);
            if (this._shape.onLoad) {
              this._shape.onLoad();
            }
            this._body = this.getComponent(RigidBody2D);
          }
        }
        onEnable() {
          if (this._shape) {
            this._shape.onEnable();
          }
        }
        onDisable() {
          if (this._shape && this._shape.onDisable) {
            this._shape.onDisable();
          }
        }
        onDestroy() {
          if (this._shape && this._shape.onDestroy) {
            this._shape.onDestroy();
          }
        }
        apply() {
          if (this._shape && this._shape.apply) {
            this._shape.apply();
          }
        }
        get worldAABB() {
          if (this._shape) {
            return this._shape.worldAABB;
          }
          return new Rect$1();
        }
      }, (_initializer$D = applyDecoratedInitializer(_class2$E.prototype, "tag", [_dec2$F, serializable$l], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$E.prototype, "group", [_dec3$A], Object.getOwnPropertyDescriptor(_class2$E.prototype, "group"), _class2$E.prototype), _applyDecoratedDescriptor(_class2$E.prototype, "density", [_dec4$q], Object.getOwnPropertyDescriptor(_class2$E.prototype, "density"), _class2$E.prototype), _applyDecoratedDescriptor(_class2$E.prototype, "sensor", [_dec5$p], Object.getOwnPropertyDescriptor(_class2$E.prototype, "sensor"), _class2$E.prototype), _applyDecoratedDescriptor(_class2$E.prototype, "friction", [_dec6$i], Object.getOwnPropertyDescriptor(_class2$E.prototype, "friction"), _class2$E.prototype), _applyDecoratedDescriptor(_class2$E.prototype, "restitution", [_dec7$e], Object.getOwnPropertyDescriptor(_class2$E.prototype, "restitution"), _class2$E.prototype), _applyDecoratedDescriptor(_class2$E.prototype, "offset", [_dec8$9], Object.getOwnPropertyDescriptor(_class2$E.prototype, "offset"), _class2$E.prototype), _initializer2$z = applyDecoratedInitializer(_class2$E.prototype, "_group", [serializable$l], function () {
        return 1;
      }), _initializer3$r = applyDecoratedInitializer(_class2$E.prototype, "_density", [serializable$l], function () {
        return 1.0;
      }), _initializer4$o = applyDecoratedInitializer(_class2$E.prototype, "_sensor", [serializable$l], function () {
        return false;
      }), _initializer5$j = applyDecoratedInitializer(_class2$E.prototype, "_friction", [serializable$l], function () {
        return 0.2;
      }), _initializer6$f = applyDecoratedInitializer(_class2$E.prototype, "_restitution", [serializable$l], function () {
        return 0;
      }), _initializer7$c = applyDecoratedInitializer(_class2$E.prototype, "_offset", [serializable$l], function () {
        return new Vec2();
      })), _class2$E)) || _class$J));

      var _dec$I, _dec2$E, _class$I, _class2$D, _initializer$C;
      const {
        ccclass: ccclass$c,
        menu: menu$b
      } = _decorator;
      let BoxCollider2D = exports("BoxCollider2D", (_dec$I = ccclass$c('cc.BoxCollider2D'), _dec2$E = type$a(Size$1), _dec$I(_class$I = (_class2$D = class BoxCollider2D extends Collider2D {
        constructor(...args) {
          super(...args);
          this._size = _initializer$C && _initializer$C();
          this.TYPE = 1;
        }
        get size() {
          return this._size;
        }
        set size(v) {
          this._size = v;
        }
        get worldPoints() {
          if (this._shape) {
            return this._shape.worldPoints;
          }
          return [];
        }
      }, (_initializer$C = applyDecoratedInitializer(_class2$D.prototype, "_size", [serializable$l], function () {
        return new Size$1(1, 1);
      }), _applyDecoratedDescriptor(_class2$D.prototype, "size", [_dec2$E], Object.getOwnPropertyDescriptor(_class2$D.prototype, "size"), _class2$D.prototype)), _class2$D)) || _class$I));

      var _dec$H, _dec2$D, _class$H, _class2$C, _initializer$B;
      const {
        ccclass: ccclass$b,
        menu: menu$a
      } = _decorator;
      let CircleCollider2D = exports("CircleCollider2D", (_dec$H = ccclass$b('cc.CircleCollider2D'), _dec2$D = type$a(CCFloat), _dec$H(_class$H = (_class2$C = class CircleCollider2D extends Collider2D {
        constructor(...args) {
          super(...args);
          this._radius = _initializer$B && _initializer$B();
          this.TYPE = 2;
        }
        get radius() {
          return this._radius;
        }
        set radius(v) {
          this._radius = v < 0 ? 0 : v;
        }
        get worldPosition() {
          if (this._shape) {
            return this._shape.worldPosition;
          }
          return new Vec2();
        }
        get worldRadius() {
          if (this._shape) {
            return this._shape.worldRadius;
          }
          return 0;
        }
      }, (_initializer$B = applyDecoratedInitializer(_class2$C.prototype, "_radius", [serializable$l], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$C.prototype, "radius", [_dec2$D], Object.getOwnPropertyDescriptor(_class2$C.prototype, "radius"), _class2$C.prototype)), _class2$C)) || _class$H));

      var _dec$G, _dec2$C, _dec3$z, _class$G, _class2$B, _initializer$A, _initializer2$y;
      const {
        ccclass: ccclass$a,
        menu: menu$9
      } = _decorator;
      let PolygonCollider2D = exports("PolygonCollider2D", (_dec$G = ccclass$a('cc.PolygonCollider2D'), _dec2$C = type$a(CCFloat), _dec3$z = type$a([Vec2]), _dec$G(_class$G = (_class2$B = class PolygonCollider2D extends Collider2D {
        constructor(...args) {
          super(...args);
          this.threshold = _initializer$A && _initializer$A();
          this._points = _initializer2$y && _initializer2$y();
          this.TYPE = 3;
        }
        get points() {
          return this._points;
        }
        set points(v) {
          this._points = v;
        }
        get worldPoints() {
          if (this._shape) {
            return this._shape.worldPoints;
          }
          return [];
        }
      }, (_initializer$A = applyDecoratedInitializer(_class2$B.prototype, "threshold", [_dec2$C], function () {
        return 1;
      }), _initializer2$y = applyDecoratedInitializer(_class2$B.prototype, "_points", [serializable$l], function () {
        return [new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1)];
      }), _applyDecoratedDescriptor(_class2$B.prototype, "points", [_dec3$z], Object.getOwnPropertyDescriptor(_class2$B.prototype, "points"), _class2$B.prototype)), _class2$B)) || _class$G));

      var _dec$F, _dec2$B, _class$F, _class2$A, _initializer$z, _initializer2$x, _initializer3$q, _initializer4$n;
      const {
        ccclass: ccclass$9,
        type: type$1
      } = _decorator;
      let Joint2D = exports("Joint2D", (_dec$F = ccclass$9('cc.Joint2D'), _dec2$B = type$1(RigidBody2D), _dec$F(_class$F = (_class2$A = class Joint2D extends Component {
        constructor(...args) {
          super(...args);
          this.anchor = _initializer$z && _initializer$z();
          this.connectedAnchor = _initializer2$x && _initializer2$x();
          this.collideConnected = _initializer3$q && _initializer3$q();
          this.connectedBody = _initializer4$n && _initializer4$n();
          this._body = null;
          this._joint = null;
          this.TYPE = 0;
        }
        get body() {
          return this._body;
        }
        get impl() {
          return this._joint;
        }
        onLoad() {
          {
            this._joint = createJoint(this.TYPE);
            this._joint.initialize(this);
            this._body = this.getComponent(RigidBody2D);
          }
        }
        onEnable() {
          if (this._joint && this._joint.onEnable) {
            this._joint.onEnable();
          }
        }
        onDisable() {
          if (this._joint && this._joint.onDisable) {
            this._joint.onDisable();
          }
        }
        start() {
          if (this._joint && this._joint.start) {
            this._joint.start();
          }
        }
        onDestroy() {
          if (this._joint && this._joint.onDestroy) {
            this._joint.onDestroy();
          }
        }
        apply() {
          if (this._joint && this._joint.apply) {
            this._joint.apply();
          }
        }
      }, (_initializer$z = applyDecoratedInitializer(_class2$A.prototype, "anchor", [serializable$l], function () {
        return new Vec2();
      }), _initializer2$x = applyDecoratedInitializer(_class2$A.prototype, "connectedAnchor", [serializable$l], function () {
        return new Vec2();
      }), _initializer3$q = applyDecoratedInitializer(_class2$A.prototype, "collideConnected", [serializable$l], function () {
        return false;
      }), _initializer4$n = applyDecoratedInitializer(_class2$A.prototype, "connectedBody", [_dec2$B, serializable$l], function () {
        return null;
      })), _class2$A)) || _class$F));

      var _dec$E, _dec2$A, _dec3$y, _class$E, _class2$z, _initializer$y, _initializer2$w;
      const {
        ccclass: ccclass$8,
        menu: menu$8
      } = _decorator;
      let DistanceJoint2D = exports("DistanceJoint2D", (_dec$E = ccclass$8('cc.DistanceJoint2D'), _dec2$A = type$a(CCFloat), _dec3$y = type$a(CCBoolean), _dec$E(_class$E = (_class2$z = class DistanceJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 1;
          this._maxLength = _initializer$y && _initializer$y();
          this._autoCalcDistance = _initializer2$w && _initializer2$w();
        }
        get maxLength() {
          if (this._autoCalcDistance) {
            if (this.connectedBody) {
              return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
            } else {
              return Vec3.len(this.node.worldPosition);
            }
          }
          return this._maxLength;
        }
        set maxLength(v) {
          this._maxLength = v;
          if (this._joint) {
            this._joint.setMaxLength(v);
          }
        }
        get autoCalcDistance() {
          return this._autoCalcDistance;
        }
        set autoCalcDistance(v) {
          this._autoCalcDistance = v;
        }
      }, (_applyDecoratedDescriptor(_class2$z.prototype, "maxLength", [_dec2$A], Object.getOwnPropertyDescriptor(_class2$z.prototype, "maxLength"), _class2$z.prototype), _applyDecoratedDescriptor(_class2$z.prototype, "autoCalcDistance", [_dec3$y], Object.getOwnPropertyDescriptor(_class2$z.prototype, "autoCalcDistance"), _class2$z.prototype), _initializer$y = applyDecoratedInitializer(_class2$z.prototype, "_maxLength", [serializable$l], function () {
        return 5;
      }), _initializer2$w = applyDecoratedInitializer(_class2$z.prototype, "_autoCalcDistance", [serializable$l], function () {
        return true;
      })), _class2$z)) || _class$E));

      var _dec$D, _dec2$z, _dec3$x, _dec4$p, _dec5$o, _class$D, _class2$y, _initializer$x, _initializer2$v, _initializer3$p, _initializer4$m;
      const {
        ccclass: ccclass$7,
        menu: menu$7
      } = _decorator;
      let SpringJoint2D = exports("SpringJoint2D", (_dec$D = ccclass$7('cc.SpringJoint2D'), _dec2$z = type$a(CCFloat), _dec3$x = type$a(CCFloat), _dec4$p = type$a(CCFloat), _dec5$o = type$a(CCBoolean), _dec$D(_class$D = (_class2$y = class SpringJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 2;
          this._frequency = _initializer$x && _initializer$x();
          this._dampingRatio = _initializer2$v && _initializer2$v();
          this._distance = _initializer3$p && _initializer3$p();
          this._autoCalcDistance = _initializer4$m && _initializer4$m();
        }
        get frequency() {
          return this._frequency;
        }
        set frequency(v) {
          this._frequency = v;
          if (this._joint) {
            this._joint.setFrequency(v);
          }
        }
        get dampingRatio() {
          return this._dampingRatio;
        }
        set dampingRatio(v) {
          this._dampingRatio = v;
          if (this._joint) {
            this._joint.setDampingRatio(v);
          }
        }
        get distance() {
          if (this._autoCalcDistance) {
            if (this.connectedBody) {
              return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
            } else {
              return Vec3.len(this.node.worldPosition);
            }
          }
          return this._distance;
        }
        set distance(v) {
          this._distance = v;
          if (this._joint) {
            this._joint.setDistance(v);
          }
        }
        get autoCalcDistance() {
          return this._autoCalcDistance;
        }
        set autoCalcDistance(v) {
          this._autoCalcDistance = v;
        }
      }, (_applyDecoratedDescriptor(_class2$y.prototype, "frequency", [_dec2$z], Object.getOwnPropertyDescriptor(_class2$y.prototype, "frequency"), _class2$y.prototype), _applyDecoratedDescriptor(_class2$y.prototype, "dampingRatio", [_dec3$x], Object.getOwnPropertyDescriptor(_class2$y.prototype, "dampingRatio"), _class2$y.prototype), _applyDecoratedDescriptor(_class2$y.prototype, "distance", [_dec4$p], Object.getOwnPropertyDescriptor(_class2$y.prototype, "distance"), _class2$y.prototype), _applyDecoratedDescriptor(_class2$y.prototype, "autoCalcDistance", [_dec5$o], Object.getOwnPropertyDescriptor(_class2$y.prototype, "autoCalcDistance"), _class2$y.prototype), _initializer$x = applyDecoratedInitializer(_class2$y.prototype, "_frequency", [serializable$l], function () {
        return 5;
      }), _initializer2$v = applyDecoratedInitializer(_class2$y.prototype, "_dampingRatio", [serializable$l], function () {
        return 0.7;
      }), _initializer3$p = applyDecoratedInitializer(_class2$y.prototype, "_distance", [serializable$l], function () {
        return 10;
      }), _initializer4$m = applyDecoratedInitializer(_class2$y.prototype, "_autoCalcDistance", [serializable$l], function () {
        return true;
      })), _class2$y)) || _class$D));

      var _dec$C, _dec2$y, _dec3$w, _dec4$o, _class$C, _class2$x, _initializer$w, _initializer2$u, _initializer3$o;
      const {
        ccclass: ccclass$6,
        menu: menu$6
      } = _decorator;
      let MouseJoint2D = exports("MouseJoint2D", (_dec$C = ccclass$6('cc.MouseJoint2D'), _dec2$y = type$a(CCFloat), _dec3$w = type$a(CCFloat), _dec4$o = type$a(CCFloat), _dec$C(_class$C = (_class2$x = class MouseJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 4;
          this._maxForce = _initializer$w && _initializer$w();
          this._dampingRatio = _initializer2$u && _initializer2$u();
          this._frequency = _initializer3$o && _initializer3$o();
          this._target = new Vec2();
        }
        get target() {
          return this._target;
        }
        set target(v) {
          this._target = v;
          if (this._joint) {
            this._joint.setTarget(v);
          }
        }
        get frequency() {
          return this._frequency;
        }
        set frequency(v) {
          this._frequency = v;
          if (this._joint) {
            this._joint.setFrequency(v);
          }
        }
        get dampingRatio() {
          return this._dampingRatio;
        }
        set dampingRatio(v) {
          this._dampingRatio = v;
          if (this._joint) {
            this._joint.setDampingRatio(v);
          }
        }
        get maxForce() {
          return this._maxForce;
        }
        set maxForce(v) {
          this._maxForce = v;
          if (this._joint) {
            this._joint.setMaxForce(v);
          }
        }
        update(dt) {
          this._joint.update(dt);
        }
      }, (_applyDecoratedDescriptor(_class2$x.prototype, "frequency", [_dec2$y], Object.getOwnPropertyDescriptor(_class2$x.prototype, "frequency"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "dampingRatio", [_dec3$w], Object.getOwnPropertyDescriptor(_class2$x.prototype, "dampingRatio"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "maxForce", [_dec4$o], Object.getOwnPropertyDescriptor(_class2$x.prototype, "maxForce"), _class2$x.prototype), _initializer$w = applyDecoratedInitializer(_class2$x.prototype, "_maxForce", [serializable$l], function () {
        return 1000;
      }), _initializer2$u = applyDecoratedInitializer(_class2$x.prototype, "_dampingRatio", [serializable$l], function () {
        return 0.7;
      }), _initializer3$o = applyDecoratedInitializer(_class2$x.prototype, "_frequency", [serializable$l], function () {
        return 5;
      })), _class2$x)) || _class$C));

      var _dec$B, _dec2$x, _dec3$v, _dec4$n, _dec5$n, _dec6$h, _dec7$d, _class$B, _class2$w, _initializer$v, _initializer2$t, _initializer3$n, _initializer4$l, _initializer5$i, _initializer6$e;
      const tempVec3_1 = new Vec3();
      const tempVec3_2 = new Vec3();
      const {
        ccclass: ccclass$5,
        menu: menu$5
      } = _decorator;
      let RelativeJoint2D = exports("RelativeJoint2D", (_dec$B = ccclass$5('cc.RelativeJoint2D'), _dec2$x = type$a(CCFloat), _dec3$v = type$a(CCFloat), _dec4$n = type$a(CCFloat), _dec5$n = type$a(Vec2), _dec6$h = type$a(CCFloat), _dec7$d = type$a(CCBoolean), _dec$B(_class$B = (_class2$w = class RelativeJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 7;
          this._maxForce = _initializer$v && _initializer$v();
          this._maxTorque = _initializer2$t && _initializer2$t();
          this._correctionFactor = _initializer3$n && _initializer3$n();
          this._angularOffset = _initializer4$l && _initializer4$l();
          this._linearOffset = _initializer5$i && _initializer5$i();
          this._autoCalcOffset = _initializer6$e && _initializer6$e();
        }
        get maxForce() {
          return this._maxForce;
        }
        set maxForce(v) {
          this._maxForce = v;
          if (this._joint) {
            this._joint.setMaxForce(v);
          }
        }
        get maxTorque() {
          return this._maxTorque;
        }
        set maxTorque(v) {
          this._maxTorque = v;
          if (this._joint) {
            this._joint.setMaxTorque(v);
          }
        }
        get correctionFactor() {
          return this._correctionFactor;
        }
        set correctionFactor(v) {
          this._correctionFactor = v;
          if (this._joint) {
            this._joint.setCorrectionFactor(v);
          }
        }
        get linearOffset() {
          if (this._autoCalcOffset) {
            if (this.connectedBody) {
              return Vec2.subtract(this._linearOffset, this.connectedBody.node.worldPosition, this.node.worldPosition);
            } else {
              return Vec2.subtract(this._linearOffset, new Vec2(0, 0), this.node.worldPosition);
            }
          }
          return this._linearOffset;
        }
        set linearOffset(v) {
          this._linearOffset.set(v);
          if (this._joint) {
            this._joint.setLinearOffset(v);
          }
        }
        get angularOffset() {
          if (this._autoCalcOffset) {
            Quat.toEuler(tempVec3_1, this.node.worldRotation);
            if (this.connectedBody) {
              Quat.toEuler(tempVec3_2, this.connectedBody.node.worldRotation);
            } else {
              Quat.toEuler(tempVec3_2, new Quat());
            }
            this._angularOffset = tempVec3_2.z - tempVec3_1.z;
          }
          return this._angularOffset;
        }
        set angularOffset(v) {
          this._angularOffset = v;
          if (this._joint) {
            this._joint.setAngularOffset(v);
          }
        }
        get autoCalcOffset() {
          return this._autoCalcOffset;
        }
        set autoCalcOffset(v) {
          this._autoCalcOffset = v;
        }
      }, (_applyDecoratedDescriptor(_class2$w.prototype, "maxForce", [_dec2$x], Object.getOwnPropertyDescriptor(_class2$w.prototype, "maxForce"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "maxTorque", [_dec3$v], Object.getOwnPropertyDescriptor(_class2$w.prototype, "maxTorque"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "correctionFactor", [_dec4$n], Object.getOwnPropertyDescriptor(_class2$w.prototype, "correctionFactor"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "linearOffset", [_dec5$n], Object.getOwnPropertyDescriptor(_class2$w.prototype, "linearOffset"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "angularOffset", [_dec6$h], Object.getOwnPropertyDescriptor(_class2$w.prototype, "angularOffset"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "autoCalcOffset", [_dec7$d], Object.getOwnPropertyDescriptor(_class2$w.prototype, "autoCalcOffset"), _class2$w.prototype), _initializer$v = applyDecoratedInitializer(_class2$w.prototype, "_maxForce", [serializable$l], function () {
        return 5;
      }), _initializer2$t = applyDecoratedInitializer(_class2$w.prototype, "_maxTorque", [serializable$l], function () {
        return 0.7;
      }), _initializer3$n = applyDecoratedInitializer(_class2$w.prototype, "_correctionFactor", [serializable$l], function () {
        return 0.3;
      }), _initializer4$l = applyDecoratedInitializer(_class2$w.prototype, "_angularOffset", [serializable$l], function () {
        return 0;
      }), _initializer5$i = applyDecoratedInitializer(_class2$w.prototype, "_linearOffset", [serializable$l], function () {
        return new Vec2();
      }), _initializer6$e = applyDecoratedInitializer(_class2$w.prototype, "_autoCalcOffset", [serializable$l], function () {
        return true;
      })), _class2$w)) || _class$B));

      var _dec$A, _dec2$w, _dec3$u, _dec4$m, _dec5$m, _dec6$g, _dec7$c, _dec8$8, _dec9$7, _class$A, _class2$v, _initializer$u, _initializer2$s, _initializer3$m, _initializer4$k, _initializer5$h, _initializer6$d, _initializer7$b, _initializer8$b;
      const tempVec2 = new Vec2();
      const {
        ccclass: ccclass$4,
        menu: menu$4
      } = _decorator;
      let SliderJoint2D = exports("SliderJoint2D", (_dec$A = ccclass$4('cc.SliderJoint2D'), _dec2$w = type$a(CCFloat), _dec3$u = type$a(CCBoolean), _dec4$m = type$a(CCBoolean), _dec5$m = type$a(CCFloat), _dec6$g = type$a(CCFloat), _dec7$c = type$a(CCBoolean), _dec8$8 = type$a(CCFloat), _dec9$7 = type$a(CCFloat), _dec$A(_class$A = (_class2$v = class SliderJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 6;
          this._angle = _initializer$u && _initializer$u();
          this._autoCalcAngle = _initializer2$s && _initializer2$s();
          this._enableMotor = _initializer3$m && _initializer3$m();
          this._maxMotorForce = _initializer4$k && _initializer4$k();
          this._motorSpeed = _initializer5$h && _initializer5$h();
          this._enableLimit = _initializer6$d && _initializer6$d();
          this._lowerLimit = _initializer7$b && _initializer7$b();
          this._upperLimit = _initializer8$b && _initializer8$b();
        }
        get angle() {
          if (this._autoCalcAngle) {
            if (this.connectedBody) {
              Vec2.subtract(tempVec2, this.connectedBody.node.worldPosition, this.node.worldPosition);
            } else {
              Vec2.subtract(tempVec2, new Vec2(0, 0), this.node.worldPosition);
            }
            this._angle = toDegree(Math.atan2(tempVec2.y, tempVec2.x));
          }
          return this._angle;
        }
        set angle(v) {
          this._angle = v;
        }
        get autoCalcAngle() {
          return this._autoCalcAngle;
        }
        set autoCalcAngle(v) {
          this._autoCalcAngle = v;
        }
        get enableMotor() {
          return this._enableMotor;
        }
        set enableMotor(v) {
          this._enableMotor = v;
        }
        get maxMotorForce() {
          return this._maxMotorForce;
        }
        set maxMotorForce(v) {
          this._maxMotorForce = v;
          if (this._joint) {
            this._joint.setMaxMotorForce(v);
          }
        }
        get motorSpeed() {
          return this._motorSpeed;
        }
        set motorSpeed(v) {
          this._motorSpeed = v;
          if (this._joint) {
            this._joint.setMotorSpeed(v);
          }
        }
        get enableLimit() {
          return this._enableLimit;
        }
        set enableLimit(v) {
          this._enableLimit = v;
        }
        get lowerLimit() {
          return this._lowerLimit;
        }
        set lowerLimit(v) {
          this._lowerLimit = v;
          if (this._joint) {
            this._joint.setLowerLimit(v);
          }
        }
        get upperLimit() {
          return this._upperLimit;
        }
        set upperLimit(v) {
          this._upperLimit = v;
          if (this._joint) {
            this._joint.setUpperLimit(v);
          }
        }
      }, (_applyDecoratedDescriptor(_class2$v.prototype, "angle", [_dec2$w], Object.getOwnPropertyDescriptor(_class2$v.prototype, "angle"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "autoCalcAngle", [_dec3$u], Object.getOwnPropertyDescriptor(_class2$v.prototype, "autoCalcAngle"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "enableMotor", [_dec4$m], Object.getOwnPropertyDescriptor(_class2$v.prototype, "enableMotor"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "maxMotorForce", [_dec5$m], Object.getOwnPropertyDescriptor(_class2$v.prototype, "maxMotorForce"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "motorSpeed", [_dec6$g], Object.getOwnPropertyDescriptor(_class2$v.prototype, "motorSpeed"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "enableLimit", [_dec7$c], Object.getOwnPropertyDescriptor(_class2$v.prototype, "enableLimit"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "lowerLimit", [_dec8$8], Object.getOwnPropertyDescriptor(_class2$v.prototype, "lowerLimit"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "upperLimit", [_dec9$7], Object.getOwnPropertyDescriptor(_class2$v.prototype, "upperLimit"), _class2$v.prototype), _initializer$u = applyDecoratedInitializer(_class2$v.prototype, "_angle", [serializable$l], function () {
        return 0;
      }), _initializer2$s = applyDecoratedInitializer(_class2$v.prototype, "_autoCalcAngle", [serializable$l], function () {
        return true;
      }), _initializer3$m = applyDecoratedInitializer(_class2$v.prototype, "_enableMotor", [serializable$l], function () {
        return false;
      }), _initializer4$k = applyDecoratedInitializer(_class2$v.prototype, "_maxMotorForce", [serializable$l], function () {
        return 1000;
      }), _initializer5$h = applyDecoratedInitializer(_class2$v.prototype, "_motorSpeed", [serializable$l], function () {
        return 1000;
      }), _initializer6$d = applyDecoratedInitializer(_class2$v.prototype, "_enableLimit", [serializable$l], function () {
        return false;
      }), _initializer7$b = applyDecoratedInitializer(_class2$v.prototype, "_lowerLimit", [serializable$l], function () {
        return 0;
      }), _initializer8$b = applyDecoratedInitializer(_class2$v.prototype, "_upperLimit", [serializable$l], function () {
        return 0;
      })), _class2$v)) || _class$A));

      var _dec$z, _dec2$v, _dec3$t, _class$z, _class2$u, _initializer$t, _initializer2$r;
      const {
        ccclass: ccclass$3,
        menu: menu$3
      } = _decorator;
      let FixedJoint2D = exports("FixedJoint2D", (_dec$z = ccclass$3('cc.FixedJoint2D'), _dec2$v = type$a(CCFloat), _dec3$t = type$a(CCFloat), _dec$z(_class$z = (_class2$u = class FixedJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 5;
          this._frequency = _initializer$t && _initializer$t();
          this._dampingRatio = _initializer2$r && _initializer2$r();
        }
        get frequency() {
          return this._frequency;
        }
        set frequency(v) {
          this._frequency = v;
          if (this._joint) {
            this._joint.setFrequency(v);
          }
        }
        get dampingRatio() {
          return this._dampingRatio;
        }
        set dampingRatio(v) {
          this._dampingRatio = v;
          if (this._joint) {
            this._joint.setDampingRatio(v);
          }
        }
      }, (_applyDecoratedDescriptor(_class2$u.prototype, "frequency", [_dec2$v], Object.getOwnPropertyDescriptor(_class2$u.prototype, "frequency"), _class2$u.prototype), _applyDecoratedDescriptor(_class2$u.prototype, "dampingRatio", [_dec3$t], Object.getOwnPropertyDescriptor(_class2$u.prototype, "dampingRatio"), _class2$u.prototype), _initializer$t = applyDecoratedInitializer(_class2$u.prototype, "_frequency", [serializable$l], function () {
        return 0.7;
      }), _initializer2$r = applyDecoratedInitializer(_class2$u.prototype, "_dampingRatio", [serializable$l], function () {
        return 0.5;
      })), _class2$u)) || _class$z));

      var _dec$y, _dec2$u, _dec3$s, _dec4$l, _dec5$l, _dec6$f, _dec7$b, _class$y, _class2$t, _initializer$s, _initializer2$q, _initializer3$l, _initializer4$j, _initializer5$g, _initializer6$c;
      const {
        ccclass: ccclass$2,
        menu: menu$2
      } = _decorator;
      let WheelJoint2D = exports("WheelJoint2D", (_dec$y = ccclass$2('cc.WheelJoint2D'), _dec2$u = type$a(CCFloat), _dec3$s = type$a(CCBoolean), _dec4$l = type$a(CCFloat), _dec5$l = type$a(CCFloat), _dec6$f = type$a(CCFloat), _dec7$b = type$a(CCFloat), _dec$y(_class$y = (_class2$t = class WheelJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 3;
          this._angle = _initializer$s && _initializer$s();
          this._enableMotor = _initializer2$q && _initializer2$q();
          this._maxMotorTorque = _initializer3$l && _initializer3$l();
          this._motorSpeed = _initializer4$j && _initializer4$j();
          this._frequency = _initializer5$g && _initializer5$g();
          this._dampingRatio = _initializer6$c && _initializer6$c();
        }
        get angle() {
          return this._angle;
        }
        set angle(v) {
          this._angle = v;
        }
        get enableMotor() {
          return this._enableMotor;
        }
        set enableMotor(v) {
          this._enableMotor = v;
          if (this._joint) {
            this._joint.enableMotor(v);
          }
        }
        get maxMotorTorque() {
          return this._maxMotorTorque;
        }
        set maxMotorTorque(v) {
          this._maxMotorTorque = v;
          if (this._joint) {
            this._joint.setMaxMotorTorque(v);
          }
        }
        get motorSpeed() {
          return this._motorSpeed;
        }
        set motorSpeed(v) {
          this._motorSpeed = v;
          if (this._joint) {
            this._joint.setMotorSpeed(v);
          }
        }
        get frequency() {
          return this._frequency;
        }
        set frequency(v) {
          this._frequency = v;
          if (this._joint) {
            this._joint.setFrequency(v);
          }
        }
        get dampingRatio() {
          return this._dampingRatio;
        }
        set dampingRatio(v) {
          this._dampingRatio = v;
          if (this._joint) {
            this._joint.setDampingRatio(v);
          }
        }
      }, (_applyDecoratedDescriptor(_class2$t.prototype, "angle", [_dec2$u], Object.getOwnPropertyDescriptor(_class2$t.prototype, "angle"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "enableMotor", [_dec3$s], Object.getOwnPropertyDescriptor(_class2$t.prototype, "enableMotor"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "maxMotorTorque", [_dec4$l], Object.getOwnPropertyDescriptor(_class2$t.prototype, "maxMotorTorque"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "motorSpeed", [_dec5$l], Object.getOwnPropertyDescriptor(_class2$t.prototype, "motorSpeed"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "frequency", [_dec6$f], Object.getOwnPropertyDescriptor(_class2$t.prototype, "frequency"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "dampingRatio", [_dec7$b], Object.getOwnPropertyDescriptor(_class2$t.prototype, "dampingRatio"), _class2$t.prototype), _initializer$s = applyDecoratedInitializer(_class2$t.prototype, "_angle", [serializable$l], function () {
        return 90;
      }), _initializer2$q = applyDecoratedInitializer(_class2$t.prototype, "_enableMotor", [serializable$l], function () {
        return false;
      }), _initializer3$l = applyDecoratedInitializer(_class2$t.prototype, "_maxMotorTorque", [serializable$l], function () {
        return 1000;
      }), _initializer4$j = applyDecoratedInitializer(_class2$t.prototype, "_motorSpeed", [serializable$l], function () {
        return 0;
      }), _initializer5$g = applyDecoratedInitializer(_class2$t.prototype, "_frequency", [serializable$l], function () {
        return 5;
      }), _initializer6$c = applyDecoratedInitializer(_class2$t.prototype, "_dampingRatio", [serializable$l], function () {
        return 0.7;
      })), _class2$t)) || _class$y));

      var _dec$x, _dec2$t, _dec3$r, _dec4$k, _dec5$k, _dec6$e, _dec7$a, _class$x, _class2$s, _initializer$r, _initializer2$p, _initializer3$k, _initializer4$i, _initializer5$f, _initializer6$b;
      const {
        ccclass: ccclass$1,
        menu: menu$1
      } = _decorator;
      let HingeJoint2D = exports("HingeJoint2D", (_dec$x = ccclass$1('cc.HingeJoint2D'), _dec2$t = type$a(CCBoolean), _dec3$r = type$a(CCFloat), _dec4$k = type$a(CCFloat), _dec5$k = type$a(CCBoolean), _dec6$e = type$a(CCFloat), _dec7$a = type$a(CCFloat), _dec$x(_class$x = (_class2$s = class HingeJoint2D extends Joint2D {
        constructor(...args) {
          super(...args);
          this.TYPE = 8;
          this._enableLimit = _initializer$r && _initializer$r();
          this._lowerAngle = _initializer2$p && _initializer2$p();
          this._upperAngle = _initializer3$k && _initializer3$k();
          this._enableMotor = _initializer4$i && _initializer4$i();
          this._maxMotorTorque = _initializer5$f && _initializer5$f();
          this._motorSpeed = _initializer6$b && _initializer6$b();
        }
        get enableLimit() {
          return this._enableLimit;
        }
        set enableLimit(v) {
          this._enableLimit = v;
        }
        get lowerAngle() {
          return this._lowerAngle;
        }
        set lowerAngle(v) {
          this._lowerAngle = v;
          if (this._joint) {
            this._joint.setLowerAngle(v);
          }
        }
        get upperAngle() {
          return this._upperAngle;
        }
        set upperAngle(v) {
          this._upperAngle = v;
          if (this._joint) {
            this._joint.setUpperAngle(v);
          }
        }
        get enableMotor() {
          return this._enableMotor;
        }
        set enableMotor(v) {
          this._enableMotor = v;
          if (this._joint) {
            this._joint.enableMotor(v);
          }
        }
        get maxMotorTorque() {
          return this._maxMotorTorque;
        }
        set maxMotorTorque(v) {
          this._maxMotorTorque = v;
          if (this._joint) {
            this._joint.setMaxMotorTorque(v);
          }
        }
        get motorSpeed() {
          return this._motorSpeed;
        }
        set motorSpeed(v) {
          this._motorSpeed = v;
          if (this._joint) {
            this._joint.setMotorSpeed(v);
          }
        }
      }, (_applyDecoratedDescriptor(_class2$s.prototype, "enableLimit", [_dec2$t], Object.getOwnPropertyDescriptor(_class2$s.prototype, "enableLimit"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "lowerAngle", [_dec3$r], Object.getOwnPropertyDescriptor(_class2$s.prototype, "lowerAngle"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "upperAngle", [_dec4$k], Object.getOwnPropertyDescriptor(_class2$s.prototype, "upperAngle"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "enableMotor", [_dec5$k], Object.getOwnPropertyDescriptor(_class2$s.prototype, "enableMotor"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "maxMotorTorque", [_dec6$e], Object.getOwnPropertyDescriptor(_class2$s.prototype, "maxMotorTorque"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "motorSpeed", [_dec7$a], Object.getOwnPropertyDescriptor(_class2$s.prototype, "motorSpeed"), _class2$s.prototype), _initializer$r = applyDecoratedInitializer(_class2$s.prototype, "_enableLimit", [serializable$l], function () {
        return false;
      }), _initializer2$p = applyDecoratedInitializer(_class2$s.prototype, "_lowerAngle", [serializable$l], function () {
        return 0;
      }), _initializer3$k = applyDecoratedInitializer(_class2$s.prototype, "_upperAngle", [serializable$l], function () {
        return 0;
      }), _initializer4$i = applyDecoratedInitializer(_class2$s.prototype, "_enableMotor", [serializable$l], function () {
        return false;
      }), _initializer5$f = applyDecoratedInitializer(_class2$s.prototype, "_maxMotorTorque", [serializable$l], function () {
        return 1000;
      }), _initializer6$b = applyDecoratedInitializer(_class2$s.prototype, "_motorSpeed", [serializable$l], function () {
        return 0;
      })), _class2$s)) || _class$x));

      const Physics2DUtils = exports("Physics2DUtils", {
        PolygonSeparator,
        PolygonPartition
      });
      cclegacy.internal.physics2d = {
        selector
      };

      const pools = [];
      const pointCache = [new Vec2(), new Vec2()];
      const b2worldmanifold = new b2$1.WorldManifold();
      const worldmanifold = {
        points: [],
        separations: [],
        normal: new Vec2()
      };
      class ManifoldPoint {
        constructor() {
          this.localPoint = new Vec2();
          this.normalImpulse = 0;
          this.tangentImpulse = 0;
        }
      }
      const manifoldPointCache = [new ManifoldPoint(), new ManifoldPoint()];
      const manifold = {
        type: 0,
        localPoint: new Vec2(),
        localNormal: new Vec2(),
        points: []
      };
      const impulse = {
        normalImpulses: [],
        tangentImpulses: []
      };
      class PhysicsContact {
        constructor() {
          this.colliderA = null;
          this.colliderB = null;
          this.disabled = false;
          this.disabledOnce = false;
          this._impulse = null;
          this._inverted = false;
          this._b2contact = null;
        }
        static get(b2contact) {
          let c = pools.pop();
          if (!c) {
            c = new PhysicsContact();
          }
          c.init(b2contact);
          return c;
        }
        static put(b2contact) {
          const c = b2contact.m_userData;
          if (!c) return;
          pools.push(c);
          c.reset();
        }
        _setImpulse(impulse) {
          this._impulse = impulse;
        }
        init(b2contact) {
          this.colliderA = b2contact.m_fixtureA.m_userData.collider;
          this.colliderB = b2contact.m_fixtureB.m_userData.collider;
          this.disabled = false;
          this.disabledOnce = false;
          this._impulse = null;
          this._inverted = false;
          this._b2contact = b2contact;
          b2contact.m_userData = this;
        }
        reset() {
          this.setTangentSpeed(0);
          this.resetFriction();
          this.resetRestitution();
          this.colliderA = null;
          this.colliderB = null;
          this.disabled = false;
          this._impulse = null;
          this._b2contact.m_userData = null;
          this._b2contact = null;
        }
        getWorldManifold() {
          const points = worldmanifold.points;
          const separations = worldmanifold.separations;
          const normal = worldmanifold.normal;
          this._b2contact.GetWorldManifold(b2worldmanifold);
          const b2points = b2worldmanifold.points;
          const b2separations = b2worldmanifold.separations;
          const count = this._b2contact.GetManifold().pointCount;
          points.length = separations.length = count;
          for (let i = 0; i < count; i++) {
            const p = pointCache[i];
            p.x = b2points[i].x * PHYSICS_2D_PTM_RATIO;
            p.y = b2points[i].y * PHYSICS_2D_PTM_RATIO;
            points[i] = p;
            separations[i] = b2separations[i] * PHYSICS_2D_PTM_RATIO;
          }
          normal.x = b2worldmanifold.normal.x;
          normal.y = b2worldmanifold.normal.y;
          if (this._inverted) {
            normal.x *= -1;
            normal.y *= -1;
          }
          return worldmanifold;
        }
        getManifold() {
          const points = manifold.points;
          const localNormal = manifold.localNormal;
          const localPoint = manifold.localPoint;
          const b2manifold = this._b2contact.GetManifold();
          const b2points = b2manifold.points;
          const count = points.length = b2manifold.pointCount;
          for (let i = 0; i < count; i++) {
            const p = manifoldPointCache[i];
            const b2p = b2points[i];
            p.localPoint.x = b2p.localPoint.x * PHYSICS_2D_PTM_RATIO;
            p.localPoint.y = b2p.localPoint.y * PHYSICS_2D_PTM_RATIO;
            p.normalImpulse = b2p.normalImpulse * PHYSICS_2D_PTM_RATIO;
            p.tangentImpulse = b2p.tangentImpulse;
            points[i] = p;
          }
          localPoint.x = b2manifold.localPoint.x * PHYSICS_2D_PTM_RATIO;
          localPoint.y = b2manifold.localPoint.y * PHYSICS_2D_PTM_RATIO;
          localNormal.x = b2manifold.localNormal.x;
          localNormal.y = b2manifold.localNormal.y;
          manifold.type = b2manifold.type;
          if (this._inverted) {
            localNormal.x *= -1;
            localNormal.y *= -1;
          }
          return manifold;
        }
        getImpulse() {
          const b2impulse = this._impulse;
          if (!b2impulse) return null;
          const normalImpulses = impulse.normalImpulses;
          const tangentImpulses = impulse.tangentImpulses;
          const count = b2impulse.count;
          for (let i = 0; i < count; i++) {
            normalImpulses[i] = b2impulse.normalImpulses[i] * PHYSICS_2D_PTM_RATIO;
            tangentImpulses[i] = b2impulse.tangentImpulses[i];
          }
          tangentImpulses.length = normalImpulses.length = count;
          return impulse;
        }
        emit(contactType) {
          var _colliderA$body, _colliderB$body;
          const colliderA = this.colliderA;
          const colliderB = this.colliderB;
          const hasListenerA = colliderA === null || colliderA === void 0 ? void 0 : (_colliderA$body = colliderA.body) === null || _colliderA$body === void 0 ? void 0 : _colliderA$body.enabledContactListener;
          const hasListenerB = colliderB === null || colliderB === void 0 ? void 0 : (_colliderB$body = colliderB.body) === null || _colliderB$body === void 0 ? void 0 : _colliderB$body.enabledContactListener;
          if (hasListenerA) {
            colliderA.emit(contactType, colliderA, colliderB, this);
          }
          if (hasListenerB) {
            colliderB.emit(contactType, colliderB, colliderA, this);
          }
          if (hasListenerA || hasListenerB) {
            PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, this);
          }
          if (this.disabled || this.disabledOnce) {
            this.setEnabled(false);
            this.disabledOnce = false;
          }
        }
        setEnabled(value) {
          this._b2contact.SetEnabled(value);
        }
        isTouching() {
          return this._b2contact.IsTouching();
        }
        setTangentSpeed(value) {
          this._b2contact.SetTangentSpeed(value);
        }
        getTangentSpeed() {
          return this._b2contact.GetTangentSpeed();
        }
        setFriction(value) {
          this._b2contact.SetFriction(value);
        }
        getFriction() {
          return this._b2contact.GetFriction();
        }
        resetFriction() {
          return this._b2contact.ResetFriction();
        }
        setRestitution(value) {
          this._b2contact.SetRestitution(value);
        }
        getRestitution() {
          return this._b2contact.GetRestitution();
        }
        resetRestitution() {
          return this._b2contact.ResetRestitution();
        }
      }

      const _tmp_vec2 = new b2$1.Vec2();
      const _tmp_color = new Color$1();
      const GREEN_COLOR = Color$1.GREEN;
      const RED_COLOR = Color$1.RED;
      class PhysicsDebugDraw extends b2$1.Draw {
        constructor(drawer) {
          super();
          this._drawer = null;
          this._xf = new b2$1.Transform();
          this._dxf = new b2$1.Transform();
          this._drawer = drawer;
        }
        _DrawPolygon(vertices, vertexCount) {
          const drawer = this._drawer;
          for (let i = 0; i < vertexCount; i++) {
            b2$1.Transform.MulXV(this._xf, vertices[i], _tmp_vec2);
            const x = _tmp_vec2.x * PHYSICS_2D_PTM_RATIO;
            const y = _tmp_vec2.y * PHYSICS_2D_PTM_RATIO;
            if (i === 0) drawer.moveTo(x, y);else {
              drawer.lineTo(x, y);
            }
          }
          drawer.close();
        }
        DrawPolygon(vertices, vertexCount, color) {
          this._applyStrokeColor(color);
          this._DrawPolygon(vertices, vertexCount);
          this._drawer.stroke();
        }
        DrawSolidPolygon(vertices, vertexCount, color) {
          this._applyFillColor(color);
          this._DrawPolygon(vertices, vertexCount);
          this._drawer.fill();
          this._drawer.stroke();
        }
        _DrawCircle(center, radius) {
          b2$1.Transform.MulXV(this._xf, center, _tmp_vec2);
          this._drawer.circle(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO, radius * PHYSICS_2D_PTM_RATIO);
        }
        DrawCircle(center, radius, color) {
          this._applyStrokeColor(color);
          this._DrawCircle(center, radius);
          this._drawer.stroke();
        }
        DrawSolidCircle(center, radius, axis, color) {
          this._applyFillColor(color);
          this._DrawCircle(center, radius);
          this._drawer.fill();
        }
        DrawSegment(p1, p2, color) {
          const drawer = this._drawer;
          if (p1.x === p2.x && p1.y === p2.y) {
            this._applyFillColor(color);
            this._DrawCircle(p1, 2 / PHYSICS_2D_PTM_RATIO);
            drawer.fill();
            return;
          }
          this._applyStrokeColor(color);
          b2$1.Transform.MulXV(this._xf, p1, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          b2$1.Transform.MulXV(this._xf, p2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
        }
        DrawTransform(xf) {
          const drawer = this._drawer;
          drawer.strokeColor = RED_COLOR;
          _tmp_vec2.x = _tmp_vec2.y = 0;
          b2$1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          _tmp_vec2.x = 1;
          _tmp_vec2.y = 0;
          b2$1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
          drawer.strokeColor = GREEN_COLOR;
          _tmp_vec2.x = _tmp_vec2.y = 0;
          b2$1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          _tmp_vec2.x = 0;
          _tmp_vec2.y = 1;
          b2$1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
        }
        DrawPoint(center, radius, color) {}
        DrawParticles() {}
        _applyStrokeColor(color) {
          this._drawer.strokeColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
        }
        _applyFillColor(color) {
          this._drawer.fillColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
        }
        PushTransform(xf) {
          this._xf = xf;
        }
        PopTransform() {
          this._xf = this._dxf;
        }
      }

      const tempVec3$1 = new Vec3();
      const tempVec2_1$1 = new Vec2();
      const tempVec2_2 = new Vec2();
      const temoBodyDef = new b2$1.BodyDef();
      const tempB2AABB = new b2$1.AABB();
      const testResults = [];
      class b2PhysicsWorld {
        get impl() {
          return this._world;
        }
        get groundBodyImpl() {
          return this._physicsGroundBody;
        }
        constructor() {
          this._world = void 0;
          this._bodies = [];
          this._animatedBodies = [];
          this._rotationAxis = new Vec3();
          this._physicsGroundBody = void 0;
          this._contactListener = void 0;
          this._aabbQueryCallback = void 0;
          this._raycastQueryCallback = void 0;
          this._debugGraphics = null;
          this._b2DebugDrawer = null;
          this._debugDrawFlags = 0;
          this._world = new b2$1.World(new b2$1.Vec2(0, -10));
          const tempBodyDef = new b2$1.BodyDef();
          this._physicsGroundBody = this._world.CreateBody(tempBodyDef);
          const listener = new PhysicsContactListener();
          listener.setBeginContact(this._onBeginContact);
          listener.setEndContact(this._onEndContact);
          listener.setPreSolve(this._onPreSolve);
          listener.setPostSolve(this._onPostSolve);
          this._world.SetContactListener(listener);
          this._contactListener = listener;
          this._aabbQueryCallback = new PhysicsAABBQueryCallback();
          this._raycastQueryCallback = new PhysicsRayCastCallback();
        }
        get debugDrawFlags() {
          return this._debugDrawFlags;
        }
        set debugDrawFlags(v) {
          if (!v) {
            if (this._debugGraphics) {
              this._debugGraphics.node.parent = null;
            }
          }
          this._debugDrawFlags = v;
        }
        _checkDebugDrawValid() {
          if (!this._debugGraphics || !this._debugGraphics.isValid) {
            let canvas = find('Canvas');
            if (!canvas) {
              const scene = director.getScene();
              if (!scene) {
                return;
              }
              canvas = new Node$1('Canvas');
              canvas.addComponent('cc.Canvas');
              canvas.parent = scene;
            }
            const node = new Node$1('PHYSICS_2D_DEBUG_DRAW');
            node.hideFlags |= CCObject.Flags.DontSave;
            node.parent = canvas;
            node.worldPosition = Vec3.ZERO;
            node.layer = Layers.Enum.UI_2D;
            this._debugGraphics = node.addComponent('cc.Graphics');
            this._debugGraphics.lineWidth = 3;
            const debugDraw = new PhysicsDebugDraw(this._debugGraphics);
            this._b2DebugDrawer = debugDraw;
            this._world.SetDebugDraw(debugDraw);
          }
          const parent = this._debugGraphics.node.parent;
          this._debugGraphics.node.setSiblingIndex(parent.children.length - 1);
          if (this._b2DebugDrawer) {
            this._b2DebugDrawer.SetFlags(this.debugDrawFlags);
          }
        }
        setGravity(v) {
          this._world.SetGravity(v);
        }
        setAllowSleep(v) {
          this._world.SetAllowSleeping(true);
        }
        step(deltaTime, velocityIterations = 10, positionIterations = 10) {
          const animatedBodies = this._animatedBodies;
          for (let i = 0, l = animatedBodies.length; i < l; i++) {
            animatedBodies[i].animate(deltaTime);
          }
          this._world.Step(deltaTime, velocityIterations, positionIterations);
        }
        raycast(p1, p2, type, mask) {
          if (p1.equals(p2)) {
            return [];
          }
          type = type || 0;
          tempVec2_1$1.x = p1.x / PHYSICS_2D_PTM_RATIO;
          tempVec2_1$1.y = p1.y / PHYSICS_2D_PTM_RATIO;
          tempVec2_2.x = p2.x / PHYSICS_2D_PTM_RATIO;
          tempVec2_2.y = p2.y / PHYSICS_2D_PTM_RATIO;
          const callback = this._raycastQueryCallback;
          callback.init(type, mask);
          this._world.RayCast(callback, tempVec2_1$1, tempVec2_2);
          const fixtures = callback.getFixtures();
          if (fixtures.length > 0) {
            const points = callback.getPoints();
            const normals = callback.getNormals();
            const fractions = callback.getFractions();
            const results = [];
            for (let i = 0, l = fixtures.length; i < l; i++) {
              const fixture = fixtures[i];
              const shape = fixture.m_userData;
              const collider = shape.collider;
              if (type === 2) {
                let result;
                for (let j = 0; j < results.length; j++) {
                  if (results[j].collider === collider) {
                    result = results[j];
                  }
                }
                if (result) {
                  if (fractions[i] < result.fraction) {
                    result.fixtureIndex = shape.getFixtureIndex(fixture);
                    result.point.x = points[i].x * PHYSICS_2D_PTM_RATIO;
                    result.point.y = points[i].y * PHYSICS_2D_PTM_RATIO;
                    result.normal.x = normals[i].x;
                    result.normal.y = normals[i].y;
                    result.fraction = fractions[i];
                  }
                  continue;
                }
              }
              results.push({
                collider,
                fixtureIndex: shape.getFixtureIndex(fixture),
                point: new Vec2(points[i].x * PHYSICS_2D_PTM_RATIO, points[i].y * PHYSICS_2D_PTM_RATIO),
                normal: new Vec2(normals[i].x, normals[i].y),
                fraction: fractions[i]
              });
            }
            return results;
          }
          return [];
        }
        syncPhysicsToScene() {
          const bodies = this._bodies;
          for (let i = 0, l = bodies.length; i < l; i++) {
            const body = bodies[i];
            const bodyComp = body.rigidBody;
            if (bodyComp.type === 3) {
              body.resetVelocity();
              continue;
            }
            const node = bodyComp.node;
            const b2body = body.impl;
            const pos = b2body.GetPosition();
            tempVec3$1.x = pos.x * PHYSICS_2D_PTM_RATIO;
            tempVec3$1.y = pos.y * PHYSICS_2D_PTM_RATIO;
            tempVec3$1.z = 0;
            node.worldPosition = tempVec3$1;
            const angle = toDegree(b2body.GetAngle());
            node.setWorldRotationFromEuler(0, 0, angle);
          }
        }
        syncSceneToPhysics() {
          const bodies = this._bodies;
          for (let i = 0; i < bodies.length; i++) {
            bodies[i].syncSceneToPhysics();
          }
        }
        addBody(body) {
          const bodies = this._bodies;
          if (bodies.includes(body)) {
            return;
          }
          const bodyDef = temoBodyDef;
          const comp = body.rigidBody;
          bodyDef.allowSleep = comp.allowSleep;
          bodyDef.gravityScale = comp.gravityScale;
          bodyDef.linearDamping = comp.linearDamping;
          bodyDef.angularDamping = comp.angularDamping;
          bodyDef.fixedRotation = comp.fixedRotation;
          bodyDef.bullet = comp.bullet;
          const node = comp.node;
          const pos = node.worldPosition;
          bodyDef.position.Set(pos.x / PHYSICS_2D_PTM_RATIO, pos.y / PHYSICS_2D_PTM_RATIO);
          tempVec3$1.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation);
          if (this._rotationAxis.z < 0.0) {
            tempVec3$1.z = Math.PI * 2 - tempVec3$1.z;
          }
          bodyDef.angle = tempVec3$1.z;
          bodyDef.awake = comp.awakeOnLoad;
          if (comp.type === 3) {
            bodyDef.type = 1;
            this._animatedBodies.push(body);
            body._animatedPos.set(bodyDef.position.x, bodyDef.position.y);
            body._animatedAngle = bodyDef.angle;
          } else {
            bodyDef.type = comp.type;
          }
          const compPrivate = comp;
          const linearVelocity = compPrivate._linearVelocity;
          bodyDef.linearVelocity.Set(linearVelocity.x, linearVelocity.y);
          bodyDef.angularVelocity = compPrivate._angularVelocity;
          const b2Body = this._world.CreateBody(bodyDef);
          b2Body.m_userData = body;
          body._imp = b2Body;
          this._bodies.push(body);
        }
        removeBody(body) {
          if (!this._bodies.includes(body)) {
            return;
          }
          if (body.impl) {
            body.impl.m_userData = null;
            this._world.DestroyBody(body.impl);
            body._imp = null;
          }
          remove(this._bodies, body);
          const comp = body.rigidBody;
          if (comp.type === 3) {
            remove(this._animatedBodies, body);
          }
        }
        _updateBodyType(body) {
          const animatedBodies = this._animatedBodies;
          const comp = body.rigidBody;
          if (comp.type !== 3) {
            remove(animatedBodies, body);
          } else {
            if (animatedBodies.includes(body)) {
              return;
            }
            animatedBodies.push(body);
          }
        }
        registerContactFixture(fixture) {
          this._contactListener.registerContactFixture(fixture);
        }
        unregisterContactFixture(fixture) {
          this._contactListener.unregisterContactFixture(fixture);
        }
        testPoint(point) {
          const x = tempVec2_1$1.x = point.x / PHYSICS_2D_PTM_RATIO;
          const y = tempVec2_1$1.y = point.y / PHYSICS_2D_PTM_RATIO;
          const d = 0.2 / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.lowerBound.x = x - d;
          tempB2AABB.lowerBound.y = y - d;
          tempB2AABB.upperBound.x = x + d;
          tempB2AABB.upperBound.y = y + d;
          const callback = this._aabbQueryCallback;
          callback.init(tempVec2_1$1);
          this._world.QueryAABB(callback, tempB2AABB);
          const fixtures = callback.getFixtures();
          testResults.length = 0;
          for (let i = 0; i < fixtures.length; i++) {
            const collider = fixtures[i].m_userData.collider;
            if (!testResults.includes(collider)) {
              testResults.push(collider);
            }
          }
          return testResults;
        }
        testAABB(rect) {
          tempB2AABB.lowerBound.x = rect.xMin / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.lowerBound.y = rect.yMin / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.upperBound.x = rect.xMax / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.upperBound.y = rect.yMax / PHYSICS_2D_PTM_RATIO;
          const callback = this._aabbQueryCallback;
          callback.init();
          this._world.QueryAABB(callback, tempB2AABB);
          const fixtures = callback.getFixtures();
          testResults.length = 0;
          for (let i = 0; i < fixtures.length; i++) {
            const collider = fixtures[i].m_userData.collider;
            if (!testResults.includes(collider)) {
              testResults.push(collider);
            }
          }
          return testResults;
        }
        drawDebug() {
          this._checkDebugDrawValid();
          if (!this._debugGraphics) {
            return;
          }
          this._debugGraphics.clear();
          this._world.DrawDebugData();
        }
        _onBeginContact(b2contact) {
          const c = PhysicsContact.get(b2contact);
          c.emit(Contact2DType.BEGIN_CONTACT);
        }
        _onEndContact(b2contact) {
          const c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c.emit(Contact2DType.END_CONTACT);
          PhysicsContact.put(b2contact);
        }
        _onPreSolve(b2contact) {
          const c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c.emit(Contact2DType.PRE_SOLVE);
        }
        _onPostSolve(b2contact, impulse) {
          const c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c._setImpulse(impulse);
          c.emit(Contact2DType.POST_SOLVE);
          c._setImpulse(null);
        }
      }

      const tempVec3 = new Vec3();
      const tempVec2_1 = new b2$1.Vec2();
      class b2RigidBody2D {
        constructor() {
          this._animatedPos = new Vec2();
          this._animatedAngle = 0;
          this._body = null;
          this._rigidBody = void 0;
          this._inited = false;
        }
        get impl() {
          return this._body;
        }
        set _imp(v) {
          this._body = v;
        }
        get rigidBody() {
          return this._rigidBody;
        }
        get isAwake() {
          return this._body.IsAwake();
        }
        get isSleeping() {
          return !this._body.IsAwake();
        }
        initialize(com) {
          this._rigidBody = com;
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        }
        onDestroy() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        }
        onEnable() {
          this.setActive(true);
        }
        onDisable() {
          this.setActive(false);
        }
        nodeTransformChanged(type) {
          if (PhysicsSystem2D.instance.stepping) {
            return;
          }
          if (type & Node$1.TransformBit.SCALE) {
            const colliders = this.rigidBody.getComponents(Collider2D);
            for (let i = 0; i < colliders.length; i++) {
              colliders[i].apply();
            }
          }
          if (type & Node$1.TransformBit.POSITION) {
            this.syncPositionToPhysics(true);
          }
          if (type & Node$1.TransformBit.ROTATION) {
            this.syncRotationToPhysics(true);
          }
        }
        _init() {
          if (this._inited) {
            return;
          }
          PhysicsSystem2D.instance.physicsWorld.addBody(this);
          this.setActive(false);
          this._inited = true;
        }
        _destroy() {
          if (!this._inited) return;
          PhysicsSystem2D.instance.physicsWorld.removeBody(this);
          this._inited = false;
        }
        animate(dt) {
          const b2body = this._body;
          if (!b2body) return;
          const b2Pos = b2body.GetPosition();
          b2body.SetAwake(true);
          const timeStep = 1 / dt;
          tempVec2_1.x = (this._animatedPos.x - b2Pos.x) * timeStep;
          tempVec2_1.y = (this._animatedPos.y - b2Pos.y) * timeStep;
          b2body.SetLinearVelocity(tempVec2_1);
          let b2Rotation = b2body.GetAngle() % TWO_PI;
          if (b2Rotation > Math.PI) {
            b2Rotation -= TWO_PI;
          }
          let angularVelocity = (this._animatedAngle - b2Rotation) * timeStep;
          if (this._animatedAngle < -HALF_PI && b2Rotation > HALF_PI) {
            angularVelocity = (this._animatedAngle + TWO_PI - b2Rotation) * timeStep;
          }
          if (this._animatedAngle > HALF_PI && b2Rotation < -HALF_PI) {
            angularVelocity = (this._animatedAngle - TWO_PI - b2Rotation) * timeStep;
          }
          b2body.SetAngularVelocity(angularVelocity);
        }
        syncSceneToPhysics() {
          const dirty = this._rigidBody.node.hasChangedFlags;
          if (dirty) {
            this.nodeTransformChanged(dirty);
          }
        }
        syncPositionToPhysics(enableAnimated = false) {
          const b2body = this._body;
          if (!b2body) return;
          const pos = this._rigidBody.node.worldPosition;
          let temp;
          const bodyType = this._rigidBody.type;
          if (bodyType === 3) {
            temp = b2body.GetLinearVelocity();
          } else {
            temp = b2body.GetPosition();
          }
          temp.x = pos.x / PHYSICS_2D_PTM_RATIO;
          temp.y = pos.y / PHYSICS_2D_PTM_RATIO;
          if (bodyType === 3 && enableAnimated) {
            this._animatedPos.set(temp.x, temp.y);
          } else {
            b2body.SetTransformVec(temp, b2body.GetAngle());
          }
        }
        syncRotationToPhysics(enableAnimated = false) {
          const b2body = this._body;
          if (!b2body) return;
          const rot = this._rigidBody.node.worldRotation;
          const euler = tempVec3;
          Quat.toEulerInYXZOrder(euler, rot);
          const rotation = toRadian(euler.z);
          const bodyType = this._rigidBody.type;
          if (bodyType === 3 && enableAnimated) {
            this._animatedAngle = rotation;
          } else {
            b2body.SetTransformVec(b2body.GetPosition(), rotation);
          }
        }
        resetVelocity() {
          const b2body = this._body;
          if (!b2body) return;
          const temp = b2body.m_linearVelocity;
          temp.Set(0, 0);
          b2body.SetLinearVelocity(temp);
          b2body.SetAngularVelocity(0);
        }
        setType(v) {
          PhysicsSystem2D.instance.physicsWorld._updateBodyType(this);
          this._body.SetType(v);
        }
        setLinearDamping(v) {
          this._body.SetLinearDamping(v);
        }
        setAngularDamping(v) {
          this._body.SetAngularDamping(v);
        }
        setGravityScale(v) {
          this._body.SetGravityScale(v);
        }
        setFixedRotation(v) {
          this._body.SetFixedRotation(v);
        }
        setAllowSleep(v) {
          this._body.SetSleepingAllowed(v);
        }
        isActive() {
          return this._body.IsActive();
        }
        setActive(v) {
          if (!this._body.m_world.IsLocked()) {
            this._body.SetActive(v);
          } else {
            warn('Can not active RigidBody in contract listener.');
          }
        }
        wakeUp() {
          this._body.SetAwake(true);
        }
        sleep() {
          this._body.SetAwake(false);
        }
        getMass() {
          return this._body.GetMass();
        }
        setLinearVelocity(v) {
          this._body.SetLinearVelocity(v);
        }
        getLinearVelocity(out) {
          const velocity = this._body.GetLinearVelocity();
          out.x = velocity.x;
          out.y = velocity.y;
          return out;
        }
        getLinearVelocityFromWorldPoint(worldPoint, out) {
          tempVec2_1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLinearVelocityFromWorldPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        }
        setAngularVelocity(v) {
          this._body.SetAngularVelocity(v);
        }
        getAngularVelocity() {
          return this._body.GetAngularVelocity();
        }
        getLocalVector(worldVector, out) {
          out = out || new Vec2();
          tempVec2_1.Set(worldVector.x / PHYSICS_2D_PTM_RATIO, worldVector.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLocalVector(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getWorldVector(localVector, out) {
          tempVec2_1.Set(localVector.x / PHYSICS_2D_PTM_RATIO, localVector.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetWorldVector(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getLocalPoint(worldPoint, out) {
          out = out || new Vec2();
          tempVec2_1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLocalPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getWorldPoint(localPoint, out) {
          out = out || new Vec2();
          tempVec2_1.Set(localPoint.x / PHYSICS_2D_PTM_RATIO, localPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetWorldPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getLocalCenter(out) {
          out = out || new Vec2();
          const pos = this._body.GetLocalCenter();
          out.x = pos.x * PHYSICS_2D_PTM_RATIO;
          out.y = pos.y * PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getWorldCenter(out) {
          out = out || new Vec2();
          const pos = this._body.GetWorldCenter();
          out.x = pos.x * PHYSICS_2D_PTM_RATIO;
          out.y = pos.y * PHYSICS_2D_PTM_RATIO;
          return out;
        }
        getInertia() {
          return this._body.GetInertia();
        }
        applyForce(force, point, wake) {
          if (this._body) {
            tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);
            this._body.ApplyForce(force, tempVec2_1, wake);
          }
        }
        applyForceToCenter(force, wake) {
          if (this._body) {
            this._body.ApplyForceToCenter(force, wake);
          }
        }
        applyTorque(torque, wake) {
          if (this._body) {
            this._body.ApplyTorque(torque, wake);
          }
        }
        applyLinearImpulse(impulse, point, wake) {
          if (this._body) {
            tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);
            this._body.ApplyLinearImpulse(impulse, tempVec2_1, wake);
          }
        }
        applyLinearImpulseToCenter(impulse, wake) {
          if (this._body) {
            this._body.ApplyLinearImpulse(impulse, this._body.GetPosition(), wake);
          }
        }
        applyAngularImpulse(impulse, wake) {
          if (this._body) {
            this._body.ApplyAngularImpulse(impulse, wake);
          }
        }
      }

      const tempFilter = new b2$1.Filter();
      const lowerBound = new b2$1.Vec2();
      const upperBound = new b2$1.Vec2();
      function getFilter(shape) {
        const comp = shape.collider;
        if (comp.body) {
          tempFilter.categoryBits = comp.group === 1 ? comp.body.group : comp.group;
        } else {
          tempFilter.categoryBits = comp.group;
        }
        tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits];
        return tempFilter;
      }
      class b2Shape2D {
        constructor() {
          this._shapes = [];
          this._fixtures = [];
          this._collider = null;
          this._body = null;
          this._inited = false;
          this._rect = new Rect$1();
        }
        get impl() {
          return this._shapes;
        }
        get collider() {
          return this._collider;
        }
        initialize(comp) {
          this._collider = comp;
        }
        onLoad() {}
        onEnable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        }
        onDisable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        }
        start() {}
        onGroupChanged() {
          const filter = getFilter(this);
          this._fixtures.forEach(f => {
            f.SetFilterData(filter);
          });
        }
        apply() {
          this._destroy();
          if (this.collider.enabledInHierarchy) {
            this._init();
          }
        }
        get worldAABB() {
          const MAX = 10e6;
          let minX = MAX;
          let minY = MAX;
          let maxX = -MAX;
          let maxY = -MAX;
          const fixtures = this._fixtures;
          for (let i = 0; i < fixtures.length; i++) {
            const fixture = fixtures[i];
            const count = fixture.GetShape().GetChildCount();
            for (let j = 0; j < count; j++) {
              lowerBound.Copy(fixture.GetAABB(j).lowerBound);
              upperBound.Copy(fixture.GetAABB(j).upperBound);
              if (fixture.GetShape().m_type === 2) {
                const skinWidth = fixture.GetShape().m_radius;
                lowerBound.SelfAddXY(skinWidth, skinWidth);
                upperBound.SelfSubXY(skinWidth, skinWidth);
              }
              if (lowerBound.x < minX) minX = lowerBound.x;
              if (lowerBound.y < minY) minY = lowerBound.y;
              if (upperBound.x > maxX) maxX = upperBound.x;
              if (upperBound.y > maxY) maxY = upperBound.y;
            }
          }
          minX *= PHYSICS_2D_PTM_RATIO;
          minY *= PHYSICS_2D_PTM_RATIO;
          maxX *= PHYSICS_2D_PTM_RATIO;
          maxY *= PHYSICS_2D_PTM_RATIO;
          const r = this._rect;
          r.x = minX;
          r.y = minY;
          r.width = maxX - minX;
          r.height = maxY - minY;
          return r;
        }
        getFixtureIndex(fixture) {
          return this._fixtures.indexOf(fixture);
        }
        _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          return [];
        }
        _init() {
          if (this._inited) return;
          const comp = this.collider;
          const scale = comp.node.worldScale;
          let relativePosition = Vec3.ZERO;
          const body = comp.getComponent(RigidBody2D);
          if (body && body.impl && body.impl.impl) {
            this._body = body.impl.impl;
          } else {
            this._body = PhysicsSystem2D.instance.physicsWorld.groundBodyImpl;
            relativePosition = comp.node.worldPosition;
          }
          const shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y, relativePosition.x, relativePosition.y);
          const filter = getFilter(this);
          for (let i = 0; i < shapes.length; i++) {
            const shape = shapes[i];
            const fixDef = {
              density: comp.density,
              isSensor: comp.sensor,
              friction: comp.friction,
              restitution: comp.restitution,
              shape,
              filter
            };
            const fixture = this._body.CreateFixture(fixDef);
            fixture.m_userData = this;
            if (body !== null && body !== void 0 && body.enabledContactListener) {
              PhysicsSystem2D.instance.physicsWorld.registerContactFixture(fixture);
            }
            this._shapes.push(shape);
            this._fixtures.push(fixture);
          }
          this._inited = true;
        }
        _destroy() {
          if (!this._inited) return;
          const fixtures = this._fixtures;
          const body = this._body;
          for (let i = fixtures.length - 1; i >= 0; i--) {
            const fixture = fixtures[i];
            fixture.m_userData = null;
            PhysicsSystem2D.instance.physicsWorld.unregisterContactFixture(fixture);
            if (body) {
              body.DestroyFixture(fixture);
            }
          }
          this._body = null;
          this._fixtures.length = 0;
          this._shapes.length = 0;
          this._inited = false;
        }
      }

      const tempAabb = new Rect$1();
      class b2BoxShape extends b2Shape2D {
        constructor(...args) {
          super(...args);
          this._worldPoints = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
        }
        get worldPoints() {
          const aabb = tempAabb;
          const collider = this.collider;
          const size = collider.size;
          const offset = collider.offset;
          aabb.x = offset.x - size.width / 2;
          aabb.y = offset.y - size.height / 2;
          aabb.width = size.width;
          aabb.height = size.height;
          const wps = this._worldPoints;
          const wp0 = wps[0];
          const wp1 = wps[1];
          const wp2 = wps[2];
          const wp3 = wps[3];
          aabb.transformMat4ToPoints(collider.node.worldMatrix, wp0, wp1, wp2, wp3);
          return wps;
        }
        _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          scaleX = Math.abs(scaleX);
          scaleY = Math.abs(scaleY);
          const comp = this.collider;
          const width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX;
          const height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY;
          const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
          const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
          const shape = new b2$1.PolygonShape();
          shape.SetAsBox(width, height, new b2$1.Vec2(offsetX, offsetY), 0);
          return [shape];
        }
      }

      class b2CircleShape extends b2Shape2D {
        constructor(...args) {
          super(...args);
          this._worldPosition = new Vec2();
        }
        get worldRadius() {
          return this._shapes[0].m_radius * PHYSICS_2D_PTM_RATIO;
        }
        get worldPosition() {
          const p = this._shapes[0].m_p;
          return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
        }
        _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          scaleX = Math.abs(scaleX);
          scaleY = Math.abs(scaleY);
          const comp = this.collider;
          const offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
          const offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
          const shape = new b2$1.CircleShape();
          shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX;
          shape.m_p.Set(offsetX, offsetY);
          return [shape];
        }
      }

      class b2PolygonShape extends b2Shape2D {
        constructor(...args) {
          super(...args);
          this._worldPoints = [];
        }
        get worldPoints() {
          const comp = this.collider;
          const points = comp.points;
          const worldPoints = this._worldPoints;
          const m = comp.node.worldMatrix;
          for (let i = 0; i < points.length; i++) {
            if (!worldPoints[i]) {
              worldPoints[i] = new Vec2();
            }
            Vec2.transformMat4(worldPoints[i], points[i], m);
          }
          worldPoints.length = points.length;
          return this._worldPoints;
        }
        _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          const shapes = [];
          const comp = this.collider;
          const points = comp.points;
          if (points.length > 0 && points[0].equals(points[points.length - 1])) {
            points.length -= 1;
          }
          const polys = ConvexPartition(points);
          if (!polys) {
            console.log('[Physics2D] b2PolygonShape failed to decompose polygon into convex polygons, node name: ', comp.node.name);
            return shapes;
          }
          const offset = comp.offset;
          for (let i = 0; i < polys.length; i++) {
            const poly = polys[i];
            let shape = null;
            let vertices = [];
            let firstVertice = null;
            for (let j = 0, l = poly.length; j < l; j++) {
              if (!shape) {
                shape = new b2$1.PolygonShape();
              }
              const p = poly[j];
              const x = (relativePositionX + (p.x + offset.x) * scaleX) / PHYSICS_2D_PTM_RATIO;
              const y = (relativePositionY + (p.y + offset.y) * scaleY) / PHYSICS_2D_PTM_RATIO;
              const v = new b2$1.Vec2(x, y);
              vertices.push(v);
              if (!firstVertice) {
                firstVertice = v;
              }
              if (vertices.length === b2$1.maxPolygonVertices) {
                shape.Set(vertices, vertices.length);
                shapes.push(shape);
                shape = null;
                if (j < l - 1) {
                  vertices = [firstVertice, vertices[vertices.length - 1]];
                }
              }
            }
            if (shape) {
              shape.Set(vertices, vertices.length);
              shapes.push(shape);
            }
          }
          return shapes;
        }
      }

      class b2Joint {
        constructor() {
          this._b2joint = null;
          this._jointComp = null;
          this._body = null;
          this._inited = false;
        }
        get impl() {
          return this._b2joint;
        }
        get comp() {
          return this._jointComp;
        }
        get body() {
          return this._body;
        }
        initialize(comp) {
          this._jointComp = comp;
        }
        onEnable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        }
        onDisable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        }
        start() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        }
        apply() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
          if (this.comp.enabledInHierarchy) {
            PhysicsSystem2D.instance._callAfterStep(this, this._init);
          }
        }
        _init() {
          if (this._inited) return;
          const comp = this._jointComp;
          if (!comp.isValid) {
            return;
          }
          this._body = comp.getComponent(RigidBody2D);
          const def = this._createJointDef();
          if (!def) {
            return;
          }
          def.bodyA = this._body.impl.impl;
          const connectedBody = comp.connectedBody;
          if (connectedBody && !connectedBody.enabledInHierarchy) {
            return;
          }
          if (!connectedBody) {
            def.bodyB = PhysicsSystem2D.instance.physicsWorld.groundBodyImpl;
          } else {
            def.bodyB = connectedBody.impl.impl;
          }
          def.collideConnected = comp.collideConnected;
          this._b2joint = PhysicsSystem2D.instance.physicsWorld.impl.CreateJoint(def);
          this._inited = true;
        }
        _destroy() {
          if (!this._inited) return;
          PhysicsSystem2D.instance.physicsWorld.impl.DestroyJoint(this._b2joint);
          this._b2joint = null;
          this._inited = false;
        }
        _createJointDef() {
          return null;
        }
        isValid() {
          return this._b2joint && this._body && this._body.impl && this._jointComp;
        }
      }

      const tempB2Vec2 = new b2$1.Vec2();
      class b2MouseJoint extends b2Joint {
        constructor(...args) {
          super(...args);
          this._touchPoint = new Vec2();
          this._isTouched = false;
        }
        setTarget(v) {
          if (this._b2joint) {
            tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO;
            tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO;
            this._b2joint.SetTarget(tempB2Vec2);
          }
        }
        setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        }
        setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        }
        setMaxForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxForce(v);
          }
        }
        _createJointDef() {
          const def = new b2$1.MouseJointDef();
          const comp = this._jointComp;
          def.target.Set(this._touchPoint.x / PHYSICS_2D_PTM_RATIO, this._touchPoint.y / PHYSICS_2D_PTM_RATIO);
          def.maxForce = comp.maxForce;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        }
        initialize(comp) {
          super.initialize(comp);
          const canvas = find('Canvas');
          if (canvas) {
            canvas.on("touch-start", this.onTouchBegan, this);
            canvas.on("touch-move", this.onTouchMove, this);
            canvas.on("touch-end", this.onTouchEnd, this);
            canvas.on("touch-cancel", this.onTouchEnd, this);
          }
        }
        onEnable() {}
        start() {}
        onTouchBegan(event) {
          this._isTouched = true;
          const target = this._touchPoint.set(event.getUILocation());
          const world = PhysicsSystem2D.instance.physicsWorld;
          const colliders = world.testPoint(target);
          if (colliders.length <= 0) return;
          const body = colliders[0].body;
          body.wakeUp();
          const comp = this._jointComp;
          comp.connectedBody = body;
          this._init();
          this.setMaxForce(comp.maxForce * body.getMass());
          this.setTarget(target);
        }
        onTouchMove(event) {
          this._touchPoint = event.getUILocation();
        }
        onTouchEnd(event) {
          this._destroy();
          this._isTouched = false;
        }
        update() {
          if (!this._isTouched || !this.isValid()) {
            return;
          }
          this.setTarget(this._touchPoint);
        }
      }

      class b2DistanceJoint extends b2Joint {
        setMaxLength(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxLength(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.RopeJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.maxLength = comp.maxLength / PHYSICS_2D_PTM_RATIO;
          return def;
        }
      }

      class b2SpringJoint extends b2Joint {
        setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        }
        setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        }
        setDistance(v) {
          if (this._b2joint) {
            this._b2joint.SetLength(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.DistanceJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.length = comp.distance / PHYSICS_2D_PTM_RATIO;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        }
      }

      class b2RelativeJoint extends b2Joint {
        setMaxForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxForce(v);
          }
        }
        setAngularOffset(v) {
          if (this._b2joint) {
            this._b2joint.SetAngularOffset(toRadian(v));
          }
        }
        setLinearOffset(v) {
          if (this._b2joint) {
            this._b2joint.SetLinearOffset(new b2$1.Vec2(v.x / PHYSICS_2D_PTM_RATIO, v.y / PHYSICS_2D_PTM_RATIO));
          }
        }
        setCorrectionFactor(v) {
          if (this._b2joint) {
            this._b2joint.m_correctionFactor = v;
          }
        }
        setMaxTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxTorque(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.MotorJointDef();
          def.linearOffset.Set(comp.linearOffset.x / PHYSICS_2D_PTM_RATIO, comp.linearOffset.y / PHYSICS_2D_PTM_RATIO);
          def.angularOffset = toRadian(comp.angularOffset);
          def.maxForce = comp.maxForce;
          def.maxTorque = comp.maxTorque;
          def.correctionFactor = comp.correctionFactor;
          return def;
        }
      }

      class b2SliderJoint extends b2Joint {
        enableLimit(v) {
          if (this._b2joint) {
            this._b2joint.EnableLimit(v);
          }
        }
        setLowerLimit(v) {
          this.updateLimits();
        }
        setUpperLimit(v) {
          this.updateLimits();
        }
        updateLimits() {
          if (this._b2joint) {
            const comp = this._jointComp;
            this._b2joint.SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO);
          }
        }
        enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        }
        setMaxMotorForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorForce(v);
          }
        }
        setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.PrismaticJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          const angle = toRadian(comp.angle);
          def.localAxisA.Set(Math.cos(angle), Math.sin(angle));
          def.referenceAngle = 0;
          def.enableLimit = comp.enableLimit;
          def.lowerTranslation = comp.lowerLimit / PHYSICS_2D_PTM_RATIO;
          def.upperTranslation = comp.upperLimit / PHYSICS_2D_PTM_RATIO;
          def.enableMotor = comp.enableMotor;
          def.maxMotorForce = comp.maxMotorForce;
          def.motorSpeed = comp.motorSpeed;
          return def;
        }
      }

      class b2FixedJoint extends b2Joint {
        setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        }
        setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.WeldJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.referenceAngle = 0;
          def.frequencyHz = comp.frequency;
          def.dampingRatio = comp.dampingRatio;
          return def;
        }
      }

      class b2WheelJoint extends b2Joint {
        setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetSpringDampingRatio(v);
          }
        }
        setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetSpringFrequencyHz(v);
          }
        }
        enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        }
        setMaxMotorTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorTorque(v);
          }
        }
        setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.WheelJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          const angle = toRadian(comp.angle);
          def.localAxisA.Set(Math.cos(angle), Math.sin(angle));
          def.maxMotorTorque = comp.maxMotorTorque;
          def.motorSpeed = toRadian(comp.motorSpeed);
          def.enableMotor = comp.enableMotor;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        }
      }

      class b2HingeJoint extends b2Joint {
        enableLimit(v) {
          if (this._b2joint) {
            this._b2joint.EnableLimit(v);
          }
        }
        setLowerAngle(v) {
          this.updateLimits();
        }
        setUpperAngle(v) {
          this.updateLimits();
        }
        updateLimits() {
          if (this._b2joint) {
            const comp = this._jointComp;
            this._b2joint.SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle));
          }
        }
        enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        }
        setMaxMotorTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorTorque(v);
          }
        }
        setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        }
        _createJointDef() {
          const comp = this._jointComp;
          const def = new b2$1.RevoluteJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.enableMotor = comp.enableMotor;
          def.maxMotorTorque = comp.maxMotorTorque;
          def.motorSpeed = toRadian(comp.motorSpeed);
          def.enableLimit = comp.enableLimit;
          def.lowerAngle = toRadian(comp.lowerAngle);
          def.upperAngle = toRadian(comp.upperAngle);
          return def;
        }
      }

      game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => {
        selector.register('box2d', {
          PhysicsWorld: b2PhysicsWorld,
          RigidBody: b2RigidBody2D,
          BoxShape: b2BoxShape,
          CircleShape: b2CircleShape,
          PolygonShape: b2PolygonShape,
          MouseJoint: b2MouseJoint,
          DistanceJoint: b2DistanceJoint,
          SpringJoint: b2SpringJoint,
          RelativeJoint: b2RelativeJoint,
          SliderJoint: b2SliderJoint,
          FixedJoint: b2FixedJoint,
          WheelJoint: b2WheelJoint,
          HingeJoint: b2HingeJoint
        });
      });

      const Mesh = jsb.Mesh;
      const IStructProto = jsb.Mesh.IStruct.prototype;
      Object.defineProperty(IStructProto, 'minPosition', {
        configurable: true,
        enumerable: true,
        get() {
          const r = this.getMinPosition();
          if (r) {
            if (!this._minPositionCache) {
              this._minPositionCache = new Vec3(r.x, r.y, r.z);
            } else {
              this._minPositionCache.set(r.x, r.y, r.z);
            }
          } else {
            this._minPositionCache = undefined;
          }
          return this._minPositionCache;
        },
        set(v) {
          this.setMinPosition(v);
        }
      });
      Object.defineProperty(IStructProto, 'maxPosition', {
        configurable: true,
        enumerable: true,
        get() {
          const r = this.getMaxPosition();
          if (r) {
            if (!this._maxPositionCache) {
              this._maxPositionCache = new Vec3(r.x, r.y, r.z);
            } else {
              this._maxPositionCache.set(r.x, r.y, r.z);
            }
          } else {
            this._maxPositionCache = undefined;
          }
          return this._maxPositionCache;
        },
        set(v) {
          this.setMaxPosition(v);
        }
      });
      const meshAssetProto = jsb.Mesh.prototype;
      meshAssetProto.createNode = null;
      const originOnLoaded = meshAssetProto.onLoaded;
      meshAssetProto._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._struct = {
          vertexBundles: [],
          primitives: []
        };
        this._minPosition = undefined;
        this._maxPosition = undefined;
      };
      Object.defineProperty(meshAssetProto, 'struct', {
        configurable: true,
        enumerable: true,
        get() {
          return this.getStruct();
        }
      });
      Object.defineProperty(meshAssetProto, 'minPosition', {
        configurable: true,
        enumerable: true,
        get() {
          const r = this.getMinPosition();
          if (r) {
            if (!this._minPosition) {
              this._minPosition = new Vec3(r.x, r.y, r.z);
            } else {
              this._minPosition.set(r.x, r.y, r.z);
            }
          } else {
            this._minPosition = undefined;
          }
          return this._minPosition;
        }
      });
      Object.defineProperty(meshAssetProto, 'maxPosition', {
        configurable: true,
        enumerable: true,
        get() {
          const r = this.getMaxPosition();
          if (r) {
            if (!this._maxPosition) {
              this._maxPosition = new Vec3(r.x, r.y, r.z);
            } else {
              this._maxPosition.set(r.x, r.y, r.z);
            }
          } else {
            this._maxPosition = undefined;
          }
          return this._maxPosition;
        }
      });
      meshAssetProto.onLoaded = function () {
        const meshStruct = this._struct;
        if (meshStruct) {
          if (meshStruct.vertexBundles.length !== 0 || meshStruct.primitives.length !== 0) {
            this.setStruct(this._struct);
          }
        }
        this._struct = null;
        originOnLoaded.apply(this);
      };
      cclegacy.Mesh = jsb.Mesh;
      patch_cc_Mesh({
        Mesh
      });

      const MorphModel = jsb.MorphModel;
      cclegacy.MorphModel = jsb.MorphModel;

      const ReflectionProbeType = {
        "NONE": 0,
        "BAKED_CUBEMAP": 1,
        "PLANAR_REFLECTION": 2,
        "BLEND_PROBES": 3,
        "BLEND_PROBES_AND_SKYBOX": 4
      };

      var _dec$w, _dec2$s, _dec3$q, _dec4$j, _dec5$j, _dec6$d, _dec7$9, _class$w, _class2$r, _initializer$q, _initializer2$o, _initializer3$j, _initializer4$h, _initializer5$e, _initializer6$a, _initializer7$a, _initializer8$a, _initializer9$9, _initializer10$8, _class3$f, _dec8$7, _dec9$6, _dec10$2, _dec11$1, _dec12$1, _dec13$1, _dec14, _dec15, _class4$3, _class5$4, _initializer11$8, _initializer12$7, _initializer13$5, _initializer14$4, _initializer15$3, _initializer16$3, _initializer17$1, _initializer18$1, _initializer19, _initializer20, _initializer21, _class6$2;
      const {
        ccclass,
        help,
        executeInEditMode,
        executionOrder,
        menu,
        visible,
        type,
        formerlySerializedAs,
        serializable,
        editable,
        disallowAnimation
      } = _decorator;
      let _phaseID = getPhaseID('specular-pass');
      function getSkinPassIndex(subModel) {
        const passes = subModel.passes;
        const r = cclegacy.rendering;
        if (isEnableEffect()) _phaseID = r.getPhaseID(r.getPassID('specular-pass'), 'default');
        for (let k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID || isEnableEffect() && passes[k].phaseID === _phaseID) {
            return k;
          }
        }
        return -1;
      }
      const ModelShadowCastingMode = Enum({
        OFF: 0,
        ON: 1
      });
      const ModelShadowReceivingMode = Enum({
        OFF: 0,
        ON: 1
      });
      let ModelBakeSettings = (_dec$w = ccclass('cc.ModelBakeSettings'), _dec2$s = formerlySerializedAs('_recieveShadow'), _dec3$q = type(CCInteger), _dec4$j = type(CCBoolean), _dec5$j = type(CCBoolean), _dec6$d = type(Enum(ReflectionProbeType)), _dec7$9 = type(CCBoolean), _dec$w(_class$w = (_class2$r = (_class3$f = class ModelBakeSettings extends EventTarget {
        constructor() {
          super();
          this.texture = _initializer$q && _initializer$q();
          this.uvParam = _initializer2$o && _initializer2$o();
          this._bakeable = _initializer3$j && _initializer3$j();
          this._castShadow = _initializer4$h && _initializer4$h();
          this._receiveShadow = _initializer5$e && _initializer5$e();
          this._lightmapSize = _initializer6$a && _initializer6$a();
          this._useLightProbe = _initializer7$a && _initializer7$a();
          this._bakeToLightProbe = _initializer8$a && _initializer8$a();
          this._reflectionProbeType = _initializer9$9 && _initializer9$9();
          this._bakeToReflectionProbe = _initializer10$8 && _initializer10$8();
          this.probeCubemap = null;
          this.probeBlendCubemap = null;
          this.probePlanarmap = null;
        }
        get bakeable() {
          return this._bakeable;
        }
        set bakeable(val) {
          this._bakeable = val;
        }
        get castShadow() {
          return this._castShadow;
        }
        set castShadow(val) {
          this._castShadow = val;
        }
        get receiveShadow() {
          return this._receiveShadow;
        }
        set receiveShadow(val) {
          this._receiveShadow = val;
        }
        get lightmapSize() {
          return this._lightmapSize;
        }
        set lightmapSize(val) {
          this._lightmapSize = val;
        }
        get useLightProbe() {
          return this._useLightProbe;
        }
        set useLightProbe(val) {
          this._useLightProbe = val;
          this.emit("use_light_probe_changed");
        }
        get bakeToLightProbe() {
          return this._bakeToLightProbe;
        }
        set bakeToLightProbe(val) {
          this._bakeToLightProbe = val;
        }
        get reflectionProbe() {
          return this._reflectionProbeType;
        }
        set reflectionProbe(val) {
          this._reflectionProbeType = val;
          this.emit("reflection_probe_changed");
        }
        get bakeToReflectionProbe() {
          return this._bakeToReflectionProbe;
        }
        set bakeToReflectionProbe(val) {
          this._bakeToReflectionProbe = val;
          this.emit("bake_to_reflection_probe_changed");
        }
      }, _class3$f.USE_LIGHT_PROBE_CHANGED = "use_light_probe_changed", _class3$f.REFLECTION_PROBE_CHANGED = "reflection_probe_changed", _class3$f.BAKE_TO_REFLECTION_PROBE_CHANGED = "bake_to_reflection_probe_changed", _class3$f), (_initializer$q = applyDecoratedInitializer(_class2$r.prototype, "texture", [serializable], function () {
        return null;
      }), _initializer2$o = applyDecoratedInitializer(_class2$r.prototype, "uvParam", [serializable], function () {
        return new Vec4();
      }), _initializer3$j = applyDecoratedInitializer(_class2$r.prototype, "_bakeable", [serializable], function () {
        return false;
      }), _initializer4$h = applyDecoratedInitializer(_class2$r.prototype, "_castShadow", [serializable], function () {
        return false;
      }), _initializer5$e = applyDecoratedInitializer(_class2$r.prototype, "_receiveShadow", [_dec2$s], function () {
        return false;
      }), _initializer6$a = applyDecoratedInitializer(_class2$r.prototype, "_lightmapSize", [serializable], function () {
        return 64;
      }), _initializer7$a = applyDecoratedInitializer(_class2$r.prototype, "_useLightProbe", [serializable], function () {
        return false;
      }), _initializer8$a = applyDecoratedInitializer(_class2$r.prototype, "_bakeToLightProbe", [serializable], function () {
        return true;
      }), _initializer9$9 = applyDecoratedInitializer(_class2$r.prototype, "_reflectionProbeType", [serializable], function () {
        return 0;
      }), _initializer10$8 = applyDecoratedInitializer(_class2$r.prototype, "_bakeToReflectionProbe", [serializable], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$r.prototype, "lightmapSize", [_dec3$q], Object.getOwnPropertyDescriptor(_class2$r.prototype, "lightmapSize"), _class2$r.prototype), _applyDecoratedDescriptor(_class2$r.prototype, "useLightProbe", [_dec4$j], Object.getOwnPropertyDescriptor(_class2$r.prototype, "useLightProbe"), _class2$r.prototype), _applyDecoratedDescriptor(_class2$r.prototype, "bakeToLightProbe", [_dec5$j], Object.getOwnPropertyDescriptor(_class2$r.prototype, "bakeToLightProbe"), _class2$r.prototype), _applyDecoratedDescriptor(_class2$r.prototype, "reflectionProbe", [_dec6$d], Object.getOwnPropertyDescriptor(_class2$r.prototype, "reflectionProbe"), _class2$r.prototype), _applyDecoratedDescriptor(_class2$r.prototype, "bakeToReflectionProbe", [_dec7$9], Object.getOwnPropertyDescriptor(_class2$r.prototype, "bakeToReflectionProbe"), _class2$r.prototype)), _class2$r)) || _class$w);
      let MeshRenderer = (_dec8$7 = ccclass('cc.MeshRenderer'), _dec9$6 = executionOrder(100), _dec10$2 = type(CCFloat), _dec11$1 = type(CCFloat), _dec12$1 = type(ModelShadowCastingMode), _dec13$1 = type(ModelShadowReceivingMode), _dec14 = type(Mesh), _dec15 = type(CCBoolean), _dec8$7(_class4$3 = _dec9$6(_class4$3 = (_class5$4 = (_class6$2 = class MeshRenderer extends ModelRenderer {
        get shadowBias() {
          return this._shadowBias;
        }
        set shadowBias(val) {
          this._shadowBias = val;
          this._updateShadowBias();
          this._onUpdateLocalShadowBiasAndProbeId();
        }
        get shadowNormalBias() {
          return this._shadowNormalBias;
        }
        set shadowNormalBias(val) {
          this._shadowNormalBias = val;
          this._updateShadowNormalBias();
          this._onUpdateLocalShadowBiasAndProbeId();
        }
        get shadowCastingMode() {
          return this._shadowCastingMode;
        }
        set shadowCastingMode(val) {
          this._shadowCastingMode = val;
          this._updateCastShadow();
        }
        get shadowCastingModeForInspector() {
          return this.shadowCastingMode === ModelShadowCastingMode.ON;
        }
        set shadowCastingModeForInspector(val) {
          this.shadowCastingMode = val === true ? ModelShadowCastingMode.ON : ModelShadowCastingMode.OFF;
        }
        onUpdateReceiveDirLight(visibility, 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;
          }
        }
        get receiveShadow() {
          return this._shadowReceivingMode;
        }
        set receiveShadow(val) {
          this._shadowReceivingMode = val;
          this._updateReceiveShadow();
        }
        get receiveShadowForInspector() {
          return this._shadowReceivingMode === ModelShadowReceivingMode.ON;
        }
        set receiveShadowForInspector(val) {
          this._shadowReceivingMode = val === true ? ModelShadowReceivingMode.ON : ModelShadowReceivingMode.OFF;
          this._updateReceiveShadow();
        }
        get mesh() {
          return this._mesh;
        }
        set mesh(val) {
          const old = this._mesh;
          const 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();
        }
        get model() {
          return this._model;
        }
        get enableMorph() {
          return this._enableMorph;
        }
        set enableMorph(value) {
          this._enableMorph = value;
        }
        get isGlobalStandardSkinObject() {
          return this._enabledGlobalStandardSkinObject;
        }
        set isGlobalStandardSkinObject(val) {
          cclegacy.director.root.pipeline.pipelineSceneData.standardSkinMeshRenderer = val ? this : null;
          this._enabledGlobalStandardSkinObject = val;
        }
        clearGlobalStandardSkinObjectFlag() {
          this._enabledGlobalStandardSkinObject = false;
        }
        constructor() {
          super();
          this.bakeSettings = _initializer11$8 && _initializer11$8();
          this._mesh = _initializer12$7 && _initializer12$7();
          this._shadowCastingMode = _initializer13$5 && _initializer13$5();
          this._shadowReceivingMode = _initializer14$4 && _initializer14$4();
          this._shadowBias = _initializer15$3 && _initializer15$3();
          this._shadowNormalBias = _initializer16$3 && _initializer16$3();
          this._reflectionProbeId = _initializer17$1 && _initializer17$1();
          this._reflectionProbeBlendId = _initializer18$1 && _initializer18$1();
          this._reflectionProbeBlendWeight = _initializer19 && _initializer19();
          this._enabledGlobalStandardSkinObject = _initializer20 && _initializer20();
          this._reflectionProbeDataMap = null;
          this._subMeshShapesWeights = [];
          this._modelType = Model;
          this._model = null;
          this._morphInstance = null;
          this._enableMorph = _initializer21 && _initializer21();
          const highQualityMode = settings.querySettings("rendering", 'highQualityMode');
          if (highQualityMode) {
            this._shadowCastingMode = ModelShadowCastingMode.ON;
            this.bakeSettings.castShadow = true;
            this.bakeSettings.receiveShadow = true;
          }
        }
        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();
        }
        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();
        }
        onEnable() {
          super.onEnable();
          this.node.on("mobility-changed", this.onMobilityChanged, this);
          this.node.on("light-probe-baking-changed", this.onLightProbeBakingChanged, this);
          this.bakeSettings.on("use_light_probe_changed", this.onUseLightProbeChanged, this);
          this.bakeSettings.on("reflection_probe_changed", this.onReflectionProbeChanged, this);
          this.bakeSettings.on("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();
        }
        onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
          this.node.off("mobility-changed", this.onMobilityChanged, this);
          this.node.off("light-probe-baking-changed", this.onLightProbeBakingChanged, this);
          this.bakeSettings.off("use_light_probe_changed", this.onUseLightProbeChanged, this);
          this.bakeSettings.off("reflection_probe_changed", this.onReflectionProbeChanged, this);
          this.bakeSettings.off("bake_to_reflection_probe_changed", this.onBakeToReflectionProbeChanged, this);
        }
        onDestroy() {
          if (this._model) {
            cclegacy.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
          if (this._morphInstance) {
            this._morphInstance.destroy();
          }
        }
        onGeometryChanged() {
          if (this._model && this._mesh) {
            const meshStruct = this._mesh.struct;
            this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition);
            this._model.updateWorldBound();
            this._model.onGeometryChanged();
          }
        }
        getWeight(subMeshIndex, shapeIndex) {
          const {
            _subMeshShapesWeights: subMeshShapesWeights
          } = this;
          assertIsTrue(subMeshIndex < subMeshShapesWeights.length);
          const shapeWeights = this._subMeshShapesWeights[subMeshIndex];
          assertIsTrue(shapeIndex < shapeWeights.length);
          return shapeWeights[shapeIndex];
        }
        setWeights(weights, subMeshIndex) {
          const {
            _subMeshShapesWeights: subMeshShapesWeights
          } = this;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          const shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeWeights.length !== weights.length) {
            return;
          }
          subMeshShapesWeights[subMeshIndex] = weights.slice(0);
          this._uploadSubMeshShapesWeights(subMeshIndex);
        }
        setWeight(weight, subMeshIndex, shapeIndex) {
          const {
            _subMeshShapesWeights: subMeshShapesWeights
          } = this;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          const shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeIndex >= shapeWeights.length) {
            return;
          }
          shapeWeights[shapeIndex] = weight;
          this._uploadSubMeshShapesWeights(subMeshIndex);
        }
        setInstancedAttribute(name, value) {
          if (!this.model) {
            return;
          }
          {
            this.model._setInstancedAttribute(name, value);
          }
        }
        _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();
        }
        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);
          }
        }
        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);
          }
        }
        updateProbePlanarMap(planarMap) {
          if (this.bakeSettings.probePlanarmap === planarMap) {
            return;
          }
          this.bakeSettings.probePlanarmap = planarMap;
          if (this.model !== null) {
            this.model.updateReflectionProbePlanarMap(this.bakeSettings.probePlanarmap);
          }
        }
        updateReflectionProbeDataMap(dataMap) {
          this._reflectionProbeDataMap = dataMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(dataMap);
          }
        }
        updateReflectionProbeId(probeId) {
          this._reflectionProbeId = probeId;
          if (this.model) {
            this.model.reflectionProbeId = probeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        }
        updateReflectionProbeBlendId(blendProbeId) {
          this._reflectionProbeBlendId = blendProbeId;
          if (this.model) {
            this.model.reflectionProbeBlendId = blendProbeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        }
        updateReflectionProbeBlendWeight(weight) {
          this._reflectionProbeBlendWeight = weight;
          if (this.model) {
            this.model.reflectionProbeBlendWeight = weight;
          }
          this._onUpdateLocalReflectionProbeData();
        }
        _updateReflectionProbeTexture() {
          if (!this.model) return;
          const bakeSettings = this.bakeSettings;
          const reflectionProbe = bakeSettings.reflectionProbe;
          const probeBlendCubemap = bakeSettings.probeBlendCubemap;
          const probePlanarMap = bakeSettings.probePlanarmap;
          const probeCubeMap = bakeSettings.probeCubemap;
          if (reflectionProbe === 1) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbePlanarMap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          } else if (reflectionProbe === 3 || reflectionProbe === 4) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbeBlendCubemap(probeBlendCubemap);
            this.model.updateReflectionProbePlanarMap(null);
          } else if (reflectionProbe === 2) {
            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);
          }
        }
        _updateModels() {
          if (!this.enabledInHierarchy) {
            return;
          }
          const model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            if (this._mesh) {
              const 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();
          }
        }
        _updateReceiveDirLight() {
          if (!this._model) {
            return;
          }
          const scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          const mainLight = scene.renderScene.mainLight;
          if (!mainLight) {
            return;
          }
          const visibility = mainLight.visibility;
          if (!mainLight.node) {
            return;
          }
          if (mainLight.node.mobility === MobilityMode.Static) {
            let 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);
          }
        }
        _createModel() {
          const preferMorphOverPlain = !!this._morphInstance;
          const modelType = preferMorphOverPlain && this._modelType === Model ? MorphModel : this._modelType;
          const model = this._model = cclegacy.director.root.createModel(modelType);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(model);
          if (this._morphInstance && model instanceof MorphModel) {
            model.setMorphRendering(this._morphInstance);
          }
        }
        _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          const renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        }
        _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        }
        _updateModelParams() {
          if (!this._mesh || !this._model) {
            return;
          }
          this.node.hasChangedFlags |= 1;
          this._model.transform.hasChangedFlags |= 1;
          this._model.isDynamicBatching = this._isBatchingEnabled();
          const meshCount = this._mesh ? this._mesh.renderingSubMeshes.length : 0;
          const renderingMesh = this._mesh.renderingSubMeshes;
          if (renderingMesh) {
            for (let i = 0; i < meshCount; ++i) {
              let material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              const subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        }
        _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]);
        }
        _onUpdateLocalShadowBiasAndProbeId() {
          if (this.model !== null) {
            this.model.updateLocalShadowBias();
            this.model.updateReflectionProbeId();
          }
          this.setInstancedAttribute('a_localShadowBiasAndProbeId', [this._shadowBias, this._shadowNormalBias, this._reflectionProbeId, this._reflectionProbeBlendId]);
        }
        _onUpdateLocalReflectionProbeData() {
          if (this.bakeSettings.reflectionProbe === 1 || this.bakeSettings.reflectionProbe === 3 || this.bakeSettings.reflectionProbe === 4) {
            if (this.model !== null) {
              this.model.updateReflectionProbeId();
            }
            this.setInstancedAttribute('a_reflectionProbeData', [this._reflectionProbeBlendWeight, 0.0, 0.0, 0.0]);
          }
        }
        _onUpdateReflectionProbeDataMap() {
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(this._reflectionProbeDataMap);
          }
        }
        _onMaterialModified(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
          this._updateStandardSkin();
        }
        _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();
        }
        _onMeshChanged(old) {}
        _clearMaterials() {
          if (!this._model) {
            return;
          }
          const subModels = this._model.subModels;
          for (let i = 0; i < subModels.length; ++i) {
            this._onMaterialModified(i, null);
          }
        }
        _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        }
        _onVisibilityChange(val) {
          if (!this._model) {
            return;
          }
          this._model.visFlags = val;
        }
        _updateShadowBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowBias = this._shadowBias;
        }
        _updateShadowNormalBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowNormalBias = this._shadowNormalBias;
        }
        _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;
          }
        }
        _updateReceiveShadow() {
          if (!this._model) {
            return;
          }
          if (this._shadowReceivingMode === ModelShadowReceivingMode.OFF) {
            this._model.receiveShadow = false;
          } else {
            this._model.receiveShadow = true;
          }
        }
        onMobilityChanged() {
          this._updateUseLightProbe();
          this._updateReceiveDirLight();
        }
        onLightProbeBakingChanged() {
          this._updateReceiveDirLight();
        }
        onUseLightProbeChanged() {
          this._updateUseLightProbe();
        }
        onReflectionProbeChanged() {
          this._updateUseReflectionProbe();
          this._onUpdateLocalShadowBiasAndProbeId();
          const reflectionProbeManager = cclegacy.internal.reflectionProbeManager;
          const model = this._model;
          if (this.bakeSettings.reflectionProbe === 1 || this.bakeSettings.reflectionProbe === 3 || this.bakeSettings.reflectionProbe === 4) {
            reflectionProbeManager.selectReflectionProbe(model);
            if (!reflectionProbeManager.getUsedReflectionProbe(model, false)) {
              warnID(16302);
            }
          } else if (this.bakeSettings.reflectionProbe === 2) {
            reflectionProbeManager.selectPlanarReflectionProbe(model);
            if (!reflectionProbeManager.getUsedReflectionProbe(model, true)) {
              warnID(16302);
            }
          }
        }
        onBakeToReflectionProbeChanged() {
          this._updateBakeToReflectionProbe();
        }
        _updateUseLightProbe() {
          if (!this._model) {
            return;
          }
          const node = this.node;
          if (this._mesh && node && node.mobility === MobilityMode.Movable && this.bakeSettings.useLightProbe) {
            this._model.useLightProbe = true;
          } else {
            this._model.useLightProbe = false;
          }
        }
        _isBatchingEnabled() {
          for (let i = 0; i < this._materials.length; ++i) {
            const mat = this._materials[i];
            if (!mat) {
              continue;
            }
            for (let p = 0; p < mat.passes.length; ++p) {
              const pass = mat.passes[p];
              if (pass.batchingScheme) {
                return true;
              }
            }
          }
          return false;
        }
        _updateUseReflectionProbe() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
          this._updateReflectionProbeTexture();
        }
        _updateUseReflectionProbeType() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
        }
        _updateBakeToReflectionProbe() {
          if (!this._model) {
            return;
          }
          this._model.bakeToReflectionProbe = this.bakeSettings.bakeToReflectionProbe;
        }
        _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();
          const nSubMeshes = this._mesh.struct.primitives.length;
          for (let iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            this._uploadSubMeshShapesWeights(iSubMesh);
          }
          if (this._model && this._model instanceof MorphModel) {
            this._model.setMorphRendering(this._morphInstance);
          }
        }
        _initSubMeshShapesWeights() {
          const {
            _mesh: mesh
          } = this;
          this._subMeshShapesWeights.length = 0;
          if (!mesh) {
            return;
          }
          const morph = mesh.struct.morph;
          if (!morph) {
            return;
          }
          const commonWeights = morph.weights;
          this._subMeshShapesWeights = morph.subMeshMorphs.map(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);
            }
          });
        }
        _validateShapeWeights() {
          const {
            _mesh: mesh,
            _subMeshShapesWeights: subMeshShapesWeights
          } = this;
          if (!mesh || !mesh.struct.morph) {
            return subMeshShapesWeights.length === 0;
          }
          const {
            morph
          } = mesh.struct;
          if (morph.subMeshMorphs.length !== subMeshShapesWeights.length) {
            return false;
          }
          return subMeshShapesWeights.every(({
            length: shapeCount
          }, subMeshIndex) => {
            var _morph$subMeshMorphs$, _morph$subMeshMorphs$2;
            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;
          });
        }
        _uploadSubMeshShapesWeights(subMeshIndex) {
          var _this$_morphInstance;
          (_this$_morphInstance = this._morphInstance) === null || _this$_morphInstance === void 0 ? void 0 : _this$_morphInstance.setWeights(subMeshIndex, this._subMeshShapesWeights[subMeshIndex]);
        }
        _updateStandardSkin() {
          const pipelineSceneData = cclegacy.director.root.pipeline.pipelineSceneData;
          if (this._enabledGlobalStandardSkinObject) {
            pipelineSceneData.standardSkinMeshRenderer = this;
            pipelineSceneData.standardSkinModel = this.model;
          }
          if (!pipelineSceneData.skinMaterialModel && this._model) {
            const subModels = this._model.subModels;
            for (let j = 0; j < subModels.length; j++) {
              const subModel = subModels[j];
              const skinPassIdx = getSkinPassIndex(subModel);
              if (skinPassIdx < 0) {
                continue;
              }
              pipelineSceneData.skinMaterialModel = this._model;
              return;
            }
          }
        }
      }, _class6$2.ShadowCastingMode = ModelShadowCastingMode, _class6$2.ShadowReceivingMode = ModelShadowReceivingMode, _class6$2), (_initializer11$8 = applyDecoratedInitializer(_class5$4.prototype, "bakeSettings", [serializable], function () {
        return new ModelBakeSettings();
      }), _initializer12$7 = applyDecoratedInitializer(_class5$4.prototype, "_mesh", [serializable], function () {
        return null;
      }), _initializer13$5 = applyDecoratedInitializer(_class5$4.prototype, "_shadowCastingMode", [serializable], function () {
        return ModelShadowCastingMode.OFF;
      }), _initializer14$4 = applyDecoratedInitializer(_class5$4.prototype, "_shadowReceivingMode", [serializable], function () {
        return ModelShadowReceivingMode.ON;
      }), _initializer15$3 = applyDecoratedInitializer(_class5$4.prototype, "_shadowBias", [serializable], function () {
        return 0;
      }), _initializer16$3 = applyDecoratedInitializer(_class5$4.prototype, "_shadowNormalBias", [serializable], function () {
        return 0;
      }), _initializer17$1 = applyDecoratedInitializer(_class5$4.prototype, "_reflectionProbeId", [serializable], function () {
        return -1;
      }), _initializer18$1 = applyDecoratedInitializer(_class5$4.prototype, "_reflectionProbeBlendId", [serializable], function () {
        return -1;
      }), _initializer19 = applyDecoratedInitializer(_class5$4.prototype, "_reflectionProbeBlendWeight", [serializable], function () {
        return 0;
      }), _initializer20 = applyDecoratedInitializer(_class5$4.prototype, "_enabledGlobalStandardSkinObject", [serializable], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$4.prototype, "shadowBias", [_dec10$2], Object.getOwnPropertyDescriptor(_class5$4.prototype, "shadowBias"), _class5$4.prototype), _applyDecoratedDescriptor(_class5$4.prototype, "shadowNormalBias", [_dec11$1], Object.getOwnPropertyDescriptor(_class5$4.prototype, "shadowNormalBias"), _class5$4.prototype), _applyDecoratedDescriptor(_class5$4.prototype, "shadowCastingMode", [_dec12$1], Object.getOwnPropertyDescriptor(_class5$4.prototype, "shadowCastingMode"), _class5$4.prototype), _applyDecoratedDescriptor(_class5$4.prototype, "receiveShadow", [_dec13$1], Object.getOwnPropertyDescriptor(_class5$4.prototype, "receiveShadow"), _class5$4.prototype), _applyDecoratedDescriptor(_class5$4.prototype, "mesh", [_dec14], Object.getOwnPropertyDescriptor(_class5$4.prototype, "mesh"), _class5$4.prototype), _applyDecoratedDescriptor(_class5$4.prototype, "isGlobalStandardSkinObject", [_dec15], Object.getOwnPropertyDescriptor(_class5$4.prototype, "isGlobalStandardSkinObject"), _class5$4.prototype), _initializer21 = applyDecoratedInitializer(_class5$4.prototype, "_enableMorph", [serializable], function () {
        return true;
      })), _class5$4)) || _class4$3) || _class4$3);

      class Counter {
        get value() {
          return this._value;
        }
        set value(val) {
          this._value = val;
        }
        constructor(id, opts, now) {
          this._total = 0;
          this._value = 0;
          this._averageValue = 0;
          this._accumValue = 0;
          this._accumSamples = 0;
          this._id = id;
          this._opts = opts;
          this._accumStart = now;
        }
        sample(now) {
          this._average(this._value, now);
        }
        human() {
          const {
            average,
            isInteger
          } = this._opts;
          const v = average ? this._averageValue : this._value;
          return isInteger ? Math.round(v) : Math.round(v * 100) / 100;
        }
        alarm() {
          if (this._opts.below !== undefined && this._value < this._opts.below) {
            return true;
          }
          if (this._opts.over !== undefined && this._value > this._opts.over) {
            return true;
          }
          return false;
        }
        _average(v, now = 0) {
          if (this._opts.average) {
            this._accumValue += v;
            ++this._accumSamples;
            const t = now;
            if (t - this._accumStart >= this._opts.average) {
              this._averageValue = this._accumValue / this._accumSamples;
              this._accumValue = 0;
              this._accumStart = t;
              this._accumSamples = 0;
            }
          }
        }
      }

      var _dec$v, _class$v;
      let PerfCounter = (_dec$v = ccclass$H('cc.PerfCounter'), _dec$v(_class$v = class PerfCounter extends Counter {
        constructor(id, opts, now) {
          super(id, opts, now);
          this._time = now;
        }
        start(now = 0) {
          this._time = now;
        }
        end(now = 0) {
          this._value = now - this._time;
          this._average(this._value);
        }
        tick() {
          this.end();
          this.start();
        }
        frame(now) {
          const t = now;
          const e = t - this._time;
          this._total++;
          const avg = this._opts.average || 1000;
          if (e > avg) {
            this._value = this._total * 1000 / e;
            this._total = 0;
            this._time = t;
            this._average(this._value);
          }
        }
      }) || _class$v);

      const _characters = '0123456789. ';
      const _average = 500;
      const _string2offset = {
        0: 0,
        1: 1,
        2: 2,
        3: 3,
        4: 4,
        5: 5,
        6: 6,
        7: 7,
        8: 8,
        9: 9,
        '.': 10
      };
      const _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)'
        }
      };
      const _constants = {
        fontSize: 23,
        quadHeight: 0.4,
        segmentsPerLine: 8,
        textureWidth: 280,
        textureHeight: 280
      };
      class Profiler extends System {
        constructor() {
          super();
          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$1.document.createElement('canvas');
            this._ctx = this._canvas.getContext('2d');
            this._canvasArr.push(this._canvas);
          }
        }
        init() {
          const showFPS = !!settings.querySettings("profiling", 'showFPS');
          if (showFPS) {
            this.showStats();
          } else {
            this.hideStats();
          }
        }
        get _stats() {
          warnID(16381);
          return this._profilerStats;
        }
        get stats() {
          return this._profilerStats;
        }
        isShowingStats() {
          return this._showFPS;
        }
        hideStats() {
          if (this._showFPS) {
            if (this._rootNode) {
              this._rootNode.active = false;
            }
            director.off("director_before_update", this.beforeUpdate, this);
            director.off("director_after_update", this.afterUpdate, this);
            director.off("director_before_physics", this.beforePhysics, this);
            director.off("director_after_physics", this.afterPhysics, this);
            director.off("director_before_draw", this.beforeDraw, this);
            director.off("director_after_render", this.afterRender, this);
            director.off("director_after_draw", this.afterPresent, this);
            this._showFPS = false;
            director.root.pipeline.profiler = null;
            cclegacy.game.config.showFPS = false;
          }
        }
        showStats() {
          if (!this._showFPS) {
            if (!this._device) {
              const root = cclegacy.director.root;
              this._device = deviceManager.gfxDevice;
              this._swapchain = root.mainWindow.swapchain;
            }
            this.generateCanvas();
            this.generateStats();
            cclegacy.game.once(cclegacy.Game.EVENT_ENGINE_INITED, this.generateNode, this);
            cclegacy.game.on(cclegacy.Game.EVENT_RESTART, this.generateNode, this);
            if (this._rootNode) {
              this._rootNode.active = true;
            }
            director.on("director_before_update", this.beforeUpdate, this);
            director.on("director_after_update", this.afterUpdate, this);
            director.on("director_before_physics", this.beforePhysics, this);
            director.on("director_after_physics", this.afterPhysics, this);
            director.on("director_before_draw", this.beforeDraw, this);
            director.on("director_after_render", this.afterRender, this);
            director.on("director_after_draw", this.afterPresent, this);
            this._showFPS = true;
            this._canvasDone = true;
            this._statsDone = true;
            cclegacy.game.config.showFPS = true;
          }
        }
        generateCanvas() {
          if (this._canvasDone) {
            return;
          }
          const {
            textureWidth,
            textureHeight
          } = _constants;
          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(1, 4 | 2, 35, textureWidth, textureHeight));
          this._region.texExtent.width = textureWidth;
          this._region.texExtent.height = textureHeight;
        }
        generateStats() {
          if (this._statsDone || !this._ctx || !this._canvas) {
            return;
          }
          this._profilerStats = null;
          const now = performance.now();
          this._ctx.textAlign = 'left';
          let i = 0;
          for (const id in _profileInfo) {
            const 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 (let j = 0; j < _characters.length; ++j) {
            const offset = this._ctx.measureText(_characters[j]).width;
            this._eachNumWidth = Math.max(this._eachNumWidth, offset);
          }
          for (let 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);
        }
        generateNode() {
          if (this._rootNode && this._rootNode.isValid) {
            return;
          }
          this._rootNode = new Node$1('PROFILER_NODE');
          this._rootNode._objFlags = cclegacy.Object.Flags.DontSave | cclegacy.Object.Flags.HideInHierarchy;
          game.addPersistRootNode(this._rootNode);
          const managerNode = new Node$1('Profiler_Root');
          managerNode.parent = this._rootNode;
          const height = _constants.quadHeight;
          const rowHeight = height / this._totalLines;
          const lWidth = height / this._wordHeight;
          const scale = rowHeight / _constants.fontSize;
          const columnWidth = this._eachNumWidth * this._canvas.width * scale;
          const vertexPos = [0, height, 0, lWidth, height, 0, lWidth, 0, 0, 0, 0, 0];
          const vertexindices = [0, 2, 1, 0, 3, 2];
          const vertexUV = [0, 0, -1, 0, 1, 0, -1, 0, 1, this._wordHeight, -1, 0, 0, this._wordHeight, -1, 0];
          let offset = 0;
          for (let i = 0; i < this._totalLines; i++) {
            for (let 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);
              const idx = i * _constants.segmentsPerLine + j;
              const z = Math.floor(idx / 4);
              const 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
          });
          const _material = new Material$1();
          _material.initialize({
            effectName: 'util/profiler'
          });
          const pass = this.pass = _material.passes[0];
          const hTexture = pass.getBinding('mainTexture');
          const bDigits = pass.getBinding('digits');
          const 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;
        }
        beforeUpdate() {
          if (!this._profilerStats) {
            return;
          }
          const now = performance.now();
          this._profilerStats.frame.counter.start(now);
          this._profilerStats.logic.counter.start(now);
        }
        afterUpdate() {
          if (!this._profilerStats) {
            return;
          }
          const now = performance.now();
          if (director.isPaused()) {
            this._profilerStats.frame.counter.start(now);
          } else {
            this._profilerStats.logic.counter.end(now);
          }
        }
        beforePhysics() {
          if (!this._profilerStats) {
            return;
          }
          const now = performance.now();
          this._profilerStats.physics.counter.start(now);
        }
        afterPhysics() {
          if (!this._profilerStats) {
            return;
          }
          const now = performance.now();
          this._profilerStats.physics.counter.end(now);
        }
        beforeDraw() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          const surfaceTransform = this._swapchain.surfaceTransform;
          const clipSpaceSignY = this._device.capabilities.clipSpaceSignY;
          if (surfaceTransform !== this.offsetData[3]) {
            const preTransform = preTransforms[surfaceTransform];
            let x = -0.9;
            let 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;
          }
          const now = performance.now();
          this._profilerStats.render.counter.start(now);
        }
        afterRender() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          const now = performance.now();
          this._profilerStats.render.counter.end(now);
          this._profilerStats.present.counter.start(now);
        }
        afterPresent() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          const 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;
          const 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;
          let i = 0;
          const view = this.digitsData;
          for (const id in this._profilerStats) {
            const stat = this._profilerStats[id];
            stat.counter.sample(now);
            const result = stat.counter.human().toString();
            for (let j = _constants.segmentsPerLine - 1; j >= 0; j--) {
              const index = i * _constants.segmentsPerLine + j;
              const character = result[result.length - (_constants.segmentsPerLine - j)];
              let offset = _string2offset[character];
              if (offset === undefined) {
                offset = 11;
              }
              view[index] = offset;
            }
            i++;
          }
        }
      } exports("Profiler", Profiler);
      const profiler = exports("profiler", new Profiler());
      director.registerSystem('profiler', profiler, 0);
      cclegacy.profiler = profiler;

      const uploadJointData = uploadJointDataLBS;
      const MINIMUM_JOINT_TEXTURE_SIZE = 480;
      function selectJointsMediumFormat(device) {
        if (device.getFormatFeatures(44) & 2) {
          return 44;
        }
        return 35;
      }
      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) {
        const formatScale = 4 / Math.sqrt(formatSize);
        return Math.ceil(Math.max(MINIMUM_JOINT_TEXTURE_SIZE * formatScale, targetLength) / 12) * 12;
      }
      const v3_3 = new Vec3();
      const v3_4 = new Vec3();
      const v3_min = new Vec3();
      const v3_max = new Vec3();
      const m4_1$2 = new Mat4();
      const m4_2$2 = new Mat4();
      const ab_1 = new AABB();
      const Inf = Number.MAX_SAFE_INTEGER;
      class JointTexturePool {
        get pixelsPerJoint() {
          return this._pixelsPerJoint;
        }
        constructor(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;
          const format = selectJointsMediumFormat(this._device);
          this._formatSize = FormatInfos[format].size;
          this._pixelsPerJoint = 48 / this._formatSize;
          this._pool = new TextureBufferPool(device);
          this._pool.initialize({
            format,
            roundUpFn: roundUpTextureSize
          });
          this._customPool = new TextureBufferPool(device);
          this._customPool.initialize({
            format,
            roundUpFn: roundUpTextureSize
          });
        }
        clear() {
          this._pool.destroy();
          this._textureBuffers.clear();
        }
        registerCustomTextureLayouts(layouts) {
          for (let i = 0; i < layouts.length; i++) {
            const layout = layouts[i];
            let textureLength = layout.textureLength;
            if (!(this._device.getFormatFeatures(44) & 2)) {
              textureLength *= 2;
            }
            const chunkIdx = this._customPool.createChunk(textureLength);
            for (let j = 0; j < layout.contents.length; j++) {
              const content = layout.contents[j];
              const {
                skeleton
              } = content;
              this._chunkIdxMap.set(skeleton, chunkIdx);
              for (let k = 0; k < content.clips.length; k++) {
                const clip = content.clips[k];
                this._chunkIdxMap.set(skeleton ^ clip, chunkIdx);
              }
            }
          }
        }
        getDefaultPoseTexture(skeleton, mesh, skinningRoot) {
          const hash = skeleton.hash ^ 0;
          let texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          const {
            joints,
            bindposes
          } = skeleton;
          let textureBuffer = null;
          let buildTexture = false;
          const jointCount = joints.length;
          if (!texture) {
            const bufSize = jointCount * 12;
            const customChunkIdx = this._chunkIdxMap.get(hash);
            const handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * 4, customChunkIdx) : this._pool.alloc(bufSize * 4);
            if (!handle) {
              return texture;
            }
            texture = {
              pixelOffset: handle.start / this._formatSize,
              refCount: 1,
              bounds: new Map(),
              skeletonHash: skeleton.hash,
              clipHash: 0,
              readyToBeDeleted: false,
              handle
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          Vec3.set(v3_min, Inf, Inf, Inf);
          Vec3.set(v3_max, -Inf, -Inf, -Inf);
          const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          for (let j = 0, offset = 0; j < jointCount; j++, offset += 12) {
            const node = skinningRoot.getChildByPath(joints[j]);
            const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1$2) : skeleton.inverseBindposes[j];
            const bound = boneSpaceBounds[j];
            if (bound) {
              AABB.transform(ab_1, bound, mat);
              ab_1.getBoundary(v3_3, v3_4);
              Vec3.min(v3_min, v3_min, v3_3);
              Vec3.max(v3_max, v3_max, v3_4);
            }
            if (buildTexture) {
              if (node) {
                Mat4.multiply(mat, mat, bindposes[j]);
              }
              uploadJointData(textureBuffer, offset, node ? mat : Mat4.IDENTITY);
            }
          }
          const bounds = [new AABB()];
          texture.bounds.set(mesh.hash, bounds);
          AABB.fromPoints(bounds[0], v3_min, v3_max);
          if (buildTexture) {
            this._pool.update(texture.handle, textureBuffer.buffer);
            this._textureBuffers.set(hash, texture);
          }
          return texture;
        }
        getSequencePoseTexture(skeleton, clip, mesh, skinningRoot) {
          const hash = skeleton.hash ^ clip.hash;
          let texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          const {
            joints,
            bindposes
          } = skeleton;
          const clipData = SkelAnimDataHub.getOrExtract(clip);
          const {
            frames
          } = clipData;
          let textureBuffer = null;
          let buildTexture = false;
          const jointCount = joints.length;
          if (!texture) {
            const bufSize = jointCount * 12 * frames;
            const customChunkIdx = this._chunkIdxMap.get(hash);
            const handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * 4, customChunkIdx) : this._pool.alloc(bufSize * 4);
            if (!handle) {
              return null;
            }
            const 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,
              animInfos
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          const bounds = [];
          texture.bounds.set(mesh.hash, bounds);
          for (let f = 0; f < frames; f++) {
            bounds.push(new AABB(Inf, Inf, Inf, -Inf, -Inf, -Inf));
          }
          for (let f = 0, offset = 0; f < frames; f++) {
            const bound = bounds[f];
            for (let j = 0; j < jointCount; j++, offset += 12) {
              const {
                curveData,
                downstream,
                bindposeIdx,
                bindposeCorrection
              } = texture.animInfos[j];
              let mat;
              let transformValid = true;
              if (curveData && downstream) {
                mat = Mat4.multiply(m4_1$2, curveData[f], downstream);
              } else if (curveData) {
                mat = curveData[f];
              } else if (downstream) {
                mat = downstream;
              } else {
                mat = skeleton.inverseBindposes[bindposeIdx];
                transformValid = false;
              }
              const boneSpaceBound = boneSpaceBounds[j];
              if (boneSpaceBound) {
                const transform = bindposeCorrection ? Mat4.multiply(m4_2$2, mat, bindposeCorrection) : mat;
                AABB.transform(ab_1, boneSpaceBound, transform);
                ab_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$2, mat, bindposes[bindposeIdx]);
                }
                uploadJointData(textureBuffer, offset, transformValid ? m4_1$2 : 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;
        }
        releaseHandle(handle) {
          if (handle.refCount > 0) {
            handle.refCount--;
          }
          if (!handle.refCount && handle.readyToBeDeleted) {
            const hash = handle.skeletonHash ^ handle.clipHash;
            const customChunkIdx = this._chunkIdxMap.get(hash);
            (customChunkIdx !== undefined ? this._customPool : this._pool).free(handle.handle);
            if (this._textureBuffers.get(hash) === handle) {
              this._textureBuffers.delete(hash);
            }
          }
        }
        releaseSkeleton(skeleton) {
          const it = this._textureBuffers.values();
          let res = it.next();
          while (!res.done) {
            const 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();
          }
        }
        releaseAnimationClip(clip) {
          const it = this._textureBuffers.values();
          let res = it.next();
          while (!res.done) {
            const 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();
          }
        }
        _createAnimInfos(skeleton, clip, skinningRoot) {
          const animInfos = [];
          const {
            joints,
            bindposes
          } = skeleton;
          const jointCount = joints.length;
          const clipData = SkelAnimDataHub.getOrExtract(clip);
          for (let j = 0; j < jointCount; j++) {
            let animPath = joints[j];
            let source = clipData.joints[animPath];
            let animNode = skinningRoot.getChildByPath(animPath);
            let downstream;
            let correctionPath;
            while (!source) {
              const idx = animPath.lastIndexOf('/');
              animPath = animPath.substring(0, idx);
              source = clipData.joints[animPath];
              if (animNode) {
                if (!downstream) {
                  downstream = new Mat4();
                }
                Mat4.fromRTS(m4_1$2, animNode.rotation, animNode.position, animNode.scale);
                Mat4.multiply(downstream, m4_1$2, downstream);
                animNode = animNode.parent;
              } else {
                correctionPath = animPath;
              }
              if (idx < 0) {
                break;
              }
            }
            let bindposeIdx = j;
            let bindposeCorrection;
            if (correctionPath !== undefined && source) {
              bindposeIdx = j - 1;
              for (let 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,
              bindposeIdx,
              bindposeCorrection
            });
          }
          return animInfos;
        }
      }
      class JointAnimationInfo {
        constructor(device) {
          this._pool = new Map();
          this._device = void 0;
          this._device = device;
        }
        getData(nodeID = '-1') {
          const res = this._pool.get(nodeID);
          if (res) {
            return res;
          }
          const buffer = this._device.createBuffer(new BufferInfo(16 | 2, 2 | 1, UBOSkinningAnimation.SIZE, UBOSkinningAnimation.SIZE));
          const data = new Float32Array([0, 0, 0, 0]);
          buffer.update(data);
          const info = {
            buffer,
            data,
            dirty: false,
            dirtyForJSB: new Uint8Array([0]),
            currentClip: null
          };
          this._pool.set(nodeID, info);
          return info;
        }
        destroy(nodeID) {
          const info = this._pool.get(nodeID);
          if (!info) {
            return;
          }
          info.buffer.destroy();
          this._pool.delete(nodeID);
        }
        switchClip(info, clip) {
          info.currentClip = clip;
          info.data[0] = 0;
          info.buffer.update(info.data);
          info.dirty = false;
          {
            info.dirtyForJSB[0] = 0;
          }
          return info;
        }
        clear() {
          for (const info of this._pool.values()) {
            info.buffer.destroy();
          }
          this._pool.clear();
        }
      }

      class DataPoolManager {
        constructor(device) {
          this.jointTexturePool = void 0;
          this.jointAnimationInfo = void 0;
          this.jointTexturePool = new JointTexturePool(device);
          this.jointAnimationInfo = new JointAnimationInfo(device);
        }
        releaseSkeleton(skeleton) {
          this.jointTexturePool.releaseSkeleton(skeleton);
        }
        releaseAnimationClip(clip) {
          this.jointTexturePool.releaseAnimationClip(clip);
        }
        clear() {
          this.jointTexturePool.clear();
          this.jointAnimationInfo.clear();
        }
      }
      cclegacy.internal.DataPoolManager = DataPoolManager;

      const m4_1$1 = new Mat4();
      const m4_2$1 = new Mat4();
      class SkeletalAnimationState extends AnimationState$1 {
        constructor(clip, name = '') {
          super(clip, name);
          this._frames = 1;
          this._bakedDuration = 0;
          this._animInfo = null;
          this._sockets = [];
          this._animInfoMgr = void 0;
          this._parent = null;
          this._curvesInited = false;
          this._animInfoMgr = cclegacy.director.root.dataPoolManager.jointAnimationInfo;
        }
        initialize(root) {
          if (this._curveLoaded) {
            return;
          }
          this._parent = root.getComponent('cc.SkeletalAnimation');
          const baked = this._parent.useBakedAnimation;
          this._doNotCreateEval = baked;
          super.initialize(root);
          this._curvesInited = !baked;
          const {
            frames,
            samples
          } = SkelAnimDataHub.getOrExtract(this.clip);
          this._frames = frames - 1;
          this._animInfo = this._animInfoMgr.getData(root.uuid);
          this._bakedDuration = this._frames / samples;
          this.setUseBaked(baked);
        }
        onPlay() {
          super.onPlay();
          const baked = this._parent.useBakedAnimation;
          if (baked) {
            this._animInfoMgr.switchClip(this._animInfo, this.clip);
            const users = this._parent.getUsers();
            users.forEach(user => {
              user.uploadAnimation(this.clip);
            });
          }
        }
        setUseBaked(useBaked) {
          if (useBaked) {
            this._sampleCurves = this._sampleCurvesBaked;
            this.duration = this._bakedDuration;
          } else {
            this._sampleCurves = super._sampleCurves;
            this.duration = this.clip.duration;
            if (!this._curvesInited) {
              this._curveLoaded = false;
              super.initialize(this._targetNode);
              this._curvesInited = true;
            }
          }
        }
        rebuildSocketCurves(sockets) {
          this._sockets.length = 0;
          if (!this._targetNode) {
            return;
          }
          const root = this._targetNode;
          for (let i = 0; i < sockets.length; ++i) {
            const socket = sockets[i];
            const targetNode = root.getChildByPath(socket.path);
            if (!socket.target) {
              continue;
            }
            const clipData = SkelAnimDataHub.getOrExtract(this.clip);
            let animPath = socket.path;
            let source = clipData.joints[animPath];
            let animNode = targetNode;
            let downstream;
            while (!source) {
              const 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;
              }
            }
            const curveData = source && source.transforms;
            const {
              frames
            } = clipData;
            const transforms = [];
            for (let f = 0; f < frames; f++) {
              let mat;
              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();
              }
              const 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
            });
          }
        }
        _sampleCurvesBaked(time) {
          const ratio = time / this.duration;
          const info = this._animInfo;
          const clip = this.clip;
          if (info.currentClip !== clip) {
            this._animInfoMgr.switchClip(this._animInfo, clip);
            const users = this._parent.getUsers();
            users.forEach(user => {
              user.uploadAnimation(clip);
            });
            info.data[0] = -1;
          }
          const curFrame = ratio * this._frames + 0.5 | 0;
          if (curFrame === info.data[0]) {
            return;
          }
          info.data[0] = curFrame;
          info.dirty = true;
          {
            info.dirtyForJSB[0] = 1;
          }
          for (let i = 0; i < this._sockets.length; ++i) {
            const {
              target,
              frames
            } = this._sockets[i];
            const {
              pos,
              rot,
              scale
            } = frames[curFrame];
            target.setRTS(rot, pos, scale);
          }
        }
      } exports("SkeletalAnimationState", SkeletalAnimationState);

      const Skeleton$1 = jsb.Skeleton;
      cclegacy.Skeleton = Skeleton$1;
      const skeletonProto = Skeleton$1.prototype;
      Object.defineProperty(skeletonProto, 'bindposes', {
        enumerable: true,
        configurable: true,
        get() {
          return this._bindposes;
        },
        set(v) {
          this._bindposes = v;
          this._setBindposes(v);
        }
      });
      skeletonProto._ctor = function () {
        jsb.Asset.prototype._ctor.apply(this, arguments);
        this._bindposes = [];
      };
      skeletonProto.destroy = function () {
        var _cclegacy$director$ro, _cclegacy$director$ro2;
        (_cclegacy$director$ro = cclegacy.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);
      };
      const oldSkeletonProtoOnLoaded = skeletonProto.onLoaded;
      skeletonProto.onLoaded = function () {
        this._setBindposes(this._bindposes);
        oldSkeletonProtoOnLoaded.call(this);
      };
      patch_cc_Skeleton({
        Skeleton: Skeleton$1,
        CCString,
        Mat4
      });

      const SkinningModel = jsb.SkinningModel;
      cclegacy.SkinningModel = jsb.SkinningModel;

      const BakedSkinningModel = jsb.BakedSkinningModel;
      cclegacy.BakedSkinningModel = jsb.BakedSkinningModel;
      jsb.MorphModel;
      const bakedSkinningModelProto = BakedSkinningModel.prototype;
      bakedSkinningModelProto._ctor = function () {
        jsb.Model.prototype._ctor.call(this);
        this.uploadedAnim = undefined;
        this._dataPoolManager = cclegacy.director.root.dataPoolManager;
        const jointTextureInfo = new Float32Array(4);
        const animInfo = this._dataPoolManager.jointAnimationInfo.getData();
        this._jointsMedium = {
          buffer: null,
          jointTextureInfo,
          animInfo,
          texture: null,
          boundsInfo: null
        };
        this._skeleton = null;
        this._mesh = null;
      };
      const oldDestroy = bakedSkinningModelProto.destroy;
      bakedSkinningModelProto.destroy = function () {
        this.uploadedAnim = undefined;
        this._jointsMedium.boundsInfo = null;
        this._applyJointTexture();
        oldDestroy.call(this);
      };
      const oldBindSkeleton = bakedSkinningModelProto.bindSkeleton;
      bakedSkinningModelProto.bindSkeleton = function (skeleton = null, skinningRoot = null, mesh = null) {
        this._skeleton = skeleton;
        this._mesh = mesh;
        if (!skeleton || !skinningRoot || !mesh) {
          return;
        }
        this.transform = skinningRoot;
        const resMgr = this._dataPoolManager;
        this._jointsMedium.animInfo = resMgr.jointAnimationInfo.getData(skinningRoot.uuid);
        const animInfo = this._jointsMedium.animInfo;
        this.syncAnimInfoForJS(animInfo.buffer, animInfo.data, animInfo.dirtyForJSB);
        oldBindSkeleton.apply(this, arguments);
      };
      bakedSkinningModelProto.uploadAnimation = function (anim) {
        var _texture;
        if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) {
          return;
        }
        this.uploadedAnim = anim;
        this.setUploadedAnimForJS(!!anim);
        const resMgr = this._dataPoolManager;
        let texture = null;
        let modelBounds = null;
        if (anim) {
          texture = resMgr.jointTexturePool.getSequencePoseTexture(this._skeleton, anim, this._mesh, this.transform);
          this._jointsMedium.boundsInfo = texture && texture.bounds.get(this._mesh.hash);
          modelBounds = null;
        } else {
          texture = resMgr.jointTexturePool.getDefaultPoseTexture(this._skeleton, this._mesh, this.transform);
          this._jointsMedium.boundsInfo = null;
          modelBounds = texture && texture.bounds.get(this._mesh.hash)[0];
        }
        this._applyJointTexture(texture);
        const {
          jointTextureInfo
        } = this._jointsMedium;
        const tex = (_texture = texture) === null || _texture === void 0 ? void 0 : _texture.handle.texture;
        this.syncDataForJS(this._jointsMedium.boundsInfo, modelBounds, jointTextureInfo[0], jointTextureInfo[1], jointTextureInfo[2], jointTextureInfo[3], tex, this._jointsMedium.animInfo.data);
      };
      bakedSkinningModelProto._applyJointTexture = function (texture = null) {
        const oldTex = this._jointsMedium.texture;
        if (oldTex && oldTex !== texture) {
          this._dataPoolManager.jointTexturePool.releaseHandle(oldTex);
        }
        this._jointsMedium.texture = texture;
        if (!texture) {
          return;
        }
        const {
          jointTextureInfo
        } = this._jointsMedium;
        jointTextureInfo[0] = texture.handle.texture.width;
        jointTextureInfo[1] = this._skeleton.joints.length;
        jointTextureInfo[2] = texture.pixelOffset + 0.1;
        jointTextureInfo[3] = 1 / jointTextureInfo[0];
      };

      var _dec$u, _dec2$r, _dec3$p, _dec4$i, _dec5$i, _dec6$c, _class$u, _class2$q, _initializer$p, _initializer2$n;
      let SkinnedMeshRenderer = (_dec$u = ccclass$H('cc.SkinnedMeshRenderer'), _dec2$r = executionOrder$1(100), _dec3$p = type$a(Skeleton$1), _dec4$i = type$a(Node$1), _dec5$i = type$a(Skeleton$1), _dec6$c = type$a(Node$1), _dec$u(_class$u = _dec2$r(_class$u = (_class2$q = class SkinnedMeshRenderer extends MeshRenderer {
        get skeleton() {
          return this._skeleton;
        }
        set skeleton(val) {
          if (val === this._skeleton) {
            return;
          }
          this._skeleton = val;
          this._update();
        }
        get skinningRoot() {
          return this._skinningRoot;
        }
        set skinningRoot(value) {
          if (value === this._skinningRoot) {
            return;
          }
          this._skinningRoot = value;
          this._tryBindAnimation();
          this._update();
        }
        get model() {
          return this._model;
        }
        constructor() {
          super();
          this._skeleton = _initializer$p && _initializer$p();
          this._skinningRoot = _initializer2$n && _initializer2$n();
          this._clip = null;
          this.associatedAnimation = null;
          this._modelType = BakedSkinningModel;
        }
        onLoad() {
          super.onLoad();
          this._tryBindAnimation();
        }
        onDestroy() {
          if (this.associatedAnimation) {
            this.associatedAnimation.notifySkinnedMeshRemoved(this);
            assertIsTrue(this.associatedAnimation === null);
          }
          super.onDestroy();
        }
        uploadAnimation(clip) {
          this._clip = clip;
          if (this.model && this.model.uploadAnimation) {
            this.model.uploadAnimation(clip);
          }
        }
        setUseBakedAnimation(val = true, force = false) {
          const modelType = val ? BakedSkinningModel : SkinningModel;
          if (!force && this._modelType === modelType) {
            return;
          }
          this._modelType = modelType;
          if (this._model) {
            cclegacy.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();
            }
          }
        }
        setSharedMaterial(material, index) {
          super.setSharedMaterial(material, index);
          if (this._modelType === SkinningModel) {
            this.getMaterialInstance(index);
          }
        }
        _updateModelParams() {
          this._update();
          super._updateModelParams();
        }
        _tryBindAnimation() {
          const {
            _skinningRoot: skinningRoot
          } = this;
          if (!skinningRoot) {
            return;
          }
          let skinningRootIsParent = false;
          for (let current = this.node; current; current = current.parent) {
            if (current === skinningRoot) {
              skinningRootIsParent = true;
              break;
            }
          }
          if (!skinningRootIsParent) {
            return;
          }
          const animation = skinningRoot.getComponent('cc.SkeletalAnimation');
          if (animation && animation.enabledInHierarchy) {
            animation.notifySkinnedMeshAdded(this);
          } else {
            this.setUseBakedAnimation(false);
          }
        }
        _update() {
          if (this.model) {
            this.model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh);
            if (this.model.uploadAnimation) {
              this.model.uploadAnimation(this._clip);
            }
          }
        }
      }, (_initializer$p = applyDecoratedInitializer(_class2$q.prototype, "_skeleton", [_dec3$p], function () {
        return null;
      }), _initializer2$n = applyDecoratedInitializer(_class2$q.prototype, "_skinningRoot", [_dec4$i], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$q.prototype, "skeleton", [_dec5$i], Object.getOwnPropertyDescriptor(_class2$q.prototype, "skeleton"), _class2$q.prototype), _applyDecoratedDescriptor(_class2$q.prototype, "skinningRoot", [_dec6$c], Object.getOwnPropertyDescriptor(_class2$q.prototype, "skinningRoot"), _class2$q.prototype)), _class2$q)) || _class$u) || _class$u);

      var _dec$t, _dec2$q, _dec3$o, _dec4$h, _dec5$h, _class$t, _class2$p, _initializer$o, _initializer2$m, _initializer3$i, _initializer4$g, _initializer5$d, _initializer6$9, _dec6$b, _dec7$8, _dec8$6, _dec9$5, _class4$2, _class5$3, _initializer7$9, _initializer8$9, _initializer9$8;
      const repeat$1 = n => n - Math.floor(n);
      const batch_id = new Attribute("a_batch_id", 11);
      const batch_uv = new Attribute("a_batch_uv", 21);
      const batch_extras_size = FormatInfos[batch_id.format].size + FormatInfos[batch_uv.format].size;
      let SkinnedMeshUnit = (_dec$t = ccclass$H('cc.SkinnedMeshUnit'), _dec2$q = type$a(Mesh), _dec3$o = type$a(Skeleton$1), _dec4$h = type$a(Material$1), _dec5$h = type$a(SkinnedMeshRenderer), _dec$t(_class$t = (_class2$p = class SkinnedMeshUnit {
        constructor() {
          this.mesh = _initializer$o && _initializer$o();
          this.skeleton = _initializer2$m && _initializer2$m();
          this.material = _initializer3$i && _initializer3$i();
          this._localTransform = _initializer4$g && _initializer4$g();
          this._offset = _initializer5$d && _initializer5$d();
          this._size = _initializer6$9 && _initializer6$9();
        }
        set offset(offset) {
          Vec2.copy(this._offset, offset);
        }
        get offset() {
          return this._offset;
        }
        set size(size) {
          Vec2.copy(this._size, size);
        }
        get size() {
          return this._size;
        }
        set copyFrom(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);
          }
        }
        get copyFrom() {
          return null;
        }
      }, (_initializer$o = applyDecoratedInitializer(_class2$p.prototype, "mesh", [_dec2$q], function () {
        return null;
      }), _initializer2$m = applyDecoratedInitializer(_class2$p.prototype, "skeleton", [_dec3$o], function () {
        return null;
      }), _initializer3$i = applyDecoratedInitializer(_class2$p.prototype, "material", [_dec4$h], function () {
        return null;
      }), _initializer4$g = applyDecoratedInitializer(_class2$p.prototype, "_localTransform", [serializable$l], function () {
        return new Mat4();
      }), _initializer5$d = applyDecoratedInitializer(_class2$p.prototype, "_offset", [serializable$l], function () {
        return new Vec2(0, 0);
      }), _initializer6$9 = applyDecoratedInitializer(_class2$p.prototype, "_size", [serializable$l], function () {
        return new Vec2(1, 1);
      }), _applyDecoratedDescriptor(_class2$p.prototype, "copyFrom", [_dec5$h], Object.getOwnPropertyDescriptor(_class2$p.prototype, "copyFrom"), _class2$p.prototype)), _class2$p)) || _class$t);
      const m4_local = new Mat4();
      new Mat4();
      const v3_1 = new Vec3();
      let SkinnedMeshBatchRenderer = (_dec6$b = ccclass$H('cc.SkinnedMeshBatchRenderer'), _dec7$8 = executionOrder$1(100), _dec8$6 = type$a([CCString]), _dec9$5 = type$a([SkinnedMeshUnit]), _dec6$b(_class4$2 = _dec7$8(_class4$2 = (_class5$3 = class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
        constructor() {
          super();
          this.atlasSize = _initializer7$9 && _initializer7$9();
          this.batchableTextureNames = _initializer8$9 && _initializer8$9();
          this.units = _initializer9$8 && _initializer9$8();
          this._textures = {};
          this._batchMaterial = null;
        }
        get mesh() {
          return super.mesh;
        }
        set mesh(val) {
          super.mesh = val;
        }
        get skeleton() {
          return super.skeleton;
        }
        set skeleton(val) {
          super.skeleton = val;
        }
        onLoad() {
          super.onLoad();
          this.cook();
        }
        onDestroy() {
          for (const tex in this._textures) {
            this._textures[tex].destroy();
          }
          this._textures = {};
          if (this._mesh) {
            this._mesh.destroy();
            this._mesh = null;
          }
          super.onDestroy();
        }
        _onMaterialModified(idx, material) {
          this.cookMaterials();
          super._onMaterialModified(idx, this.getMaterialInstance(idx));
        }
        cook() {
          this.cookMaterials();
          this.cookSkeletons();
          this.cookMeshes();
        }
        cookMaterials() {
          if (!this._batchMaterial) {
            this._batchMaterial = this.getSharedMaterial(0);
          }
          const mat = this.getMaterialInstance(0);
          if (!mat || !this._batchMaterial || !this._batchMaterial.effectAsset) {
            warn('incomplete batch material!');
            return;
          }
          mat.copy(this._batchMaterial);
          this.resizeAtlases();
          const tech = mat.effectAsset.techniques[mat.technique];
          for (let i = 0; i < tech.passes.length; i++) {
            const pass = tech.passes[i];
            if (!pass.properties) {
              continue;
            }
            for (const prop in pass.properties) {
              if (pass.properties[prop].type >= 26) {
                let tex = null;
                if (this.batchableTextureNames.find(n => n === prop)) {
                  tex = this._textures[prop];
                  if (!tex) {
                    tex = this.createTexture(prop);
                  }
                  this.cookTextures(tex, prop, i);
                } else {
                  this.units.some(u => tex = u.material && u.material.getProperty(prop, i));
                }
                if (tex) {
                  mat.setProperty(prop, tex, i);
                }
              } else {
                const value = [];
                for (let u = 0; u < this.units.length; u++) {
                  const unit = this.units[u];
                  if (!unit.material) {
                    continue;
                  }
                  value.push(unit.material.getProperty(prop.slice(0, -3), i));
                }
                mat.setProperty(prop, value, i);
              }
            }
          }
        }
        cookSkeletons() {
          if (!this._skinningRoot) {
            warn('no skinning root specified!');
            return;
          }
          const joints = [];
          const bindposes = [];
          for (let u = 0; u < this.units.length; u++) {
            const unit = this.units[u];
            if (!unit || !unit.skeleton) {
              continue;
            }
            const partial = unit.skeleton;
            Mat4.invert(m4_local, unit._localTransform);
            for (let i = 0; i < partial.joints.length; i++) {
              const path = partial.joints[i];
              const idx = joints.findIndex(p => p === path);
              if (idx >= 0) {
                continue;
              }
              joints.push(path);
              bindposes.push(Mat4.multiply(new Mat4(), partial.bindposes[i] || Mat4.IDENTITY, m4_local));
            }
          }
          const idxMap = Array.from(Array(joints.length).keys()).sort((a, b) => {
            if (joints[a] > joints[b]) {
              return 1;
            }
            if (joints[a] < joints[b]) {
              return -1;
            }
            return 0;
          });
          const skeleton = new Skeleton$1();
          skeleton.joints = joints.map((_, idx, arr) => arr[idxMap[idx]]);
          skeleton.bindposes = bindposes.map((_, idx, arr) => arr[idxMap[idx]]);
          if (this._skeleton) {
            this._skeleton.destroy();
          }
          this.skeleton = skeleton;
        }
        cookMeshes() {
          let isValid = false;
          for (let u = 0; u < this.units.length; u++) {
            const 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();
          }
          let posOffset = 0;
          let posFormat = 0;
          let normalOffset = 0;
          let normalFormat = 0;
          let tangentOffset = 0;
          let tangentFormat = 0;
          let uvOffset = 0;
          let uvFormat = 0;
          let jointOffset = 0;
          let jointFormat = 0;
          const jointIndexMap = new Array(this.units.length);
          const unitLen = this.units.length;
          for (let i = 0; i < unitLen; i++) {
            const unit = this.units[i];
            if (!unit || !unit.skeleton) {
              continue;
            }
            jointIndexMap[i] = unit.skeleton.joints.map(j => this._skeleton.joints.findIndex(ref => j === ref));
          }
          for (let i = 0; i < unitLen; i++) {
            const unit = this.units[i];
            if (!unit || !unit.mesh || !unit.mesh.data) {
              continue;
            }
            const newMesh = this._createUnitMesh(i, unit.mesh);
            const dataView = new DataView(newMesh.data.buffer);
            Mat4.invert(m4_local, unit._localTransform);
            Mat4.transpose(m4_local, m4_local);
            const {
              offset
            } = unit;
            const {
              size
            } = unit;
            for (let b = 0; b < newMesh.struct.vertexBundles.length; b++) {
              const bundle = newMesh.struct.vertexBundles[b];
              posOffset = bundle.view.offset;
              posFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_position") {
                  posFormat = attr.format;
                  break;
                }
                posOffset += FormatInfos[attr.format].size;
              }
              if (posFormat) {
                const pos = readBuffer(dataView, posFormat, posOffset, bundle.view.length, bundle.view.stride);
                for (let j = 0; j < pos.length; j += 3) {
                  Vec3.fromArray(v3_1, pos, j);
                  Vec3.transformMat4(v3_1, v3_1, unit._localTransform);
                  Vec3.toArray(pos, v3_1, j);
                }
                writeBuffer(dataView, pos, posFormat, posOffset, bundle.view.stride);
              }
              normalOffset = bundle.view.offset;
              normalFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_normal") {
                  normalFormat = attr.format;
                  break;
                }
                normalOffset += FormatInfos[attr.format].size;
              }
              if (normalFormat) {
                const normal = readBuffer(dataView, normalFormat, normalOffset, bundle.view.length, bundle.view.stride);
                for (let j = 0; j < normal.length; j += 3) {
                  Vec3.fromArray(v3_1, normal, j);
                  Vec3.transformMat4Normal(v3_1, v3_1, m4_local);
                  Vec3.toArray(normal, v3_1, j);
                }
                writeBuffer(dataView, normal, normalFormat, normalOffset, bundle.view.stride);
              }
              tangentOffset = bundle.view.offset;
              tangentFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_tangent") {
                  tangentFormat = attr.format;
                  break;
                }
                tangentOffset += FormatInfos[attr.format].size;
              }
              if (tangentFormat) {
                const tangent = readBuffer(dataView, tangentFormat, tangentOffset, bundle.view.length, bundle.view.stride);
                for (let j = 0; j < tangent.length; j += 3) {
                  Vec3.fromArray(v3_1, tangent, j);
                  Vec3.transformMat4Normal(v3_1, v3_1, m4_local);
                  Vec3.toArray(tangent, v3_1, j);
                }
                writeBuffer(dataView, tangent, tangentFormat, tangentOffset, bundle.view.stride);
              }
              uvOffset = bundle.view.offset;
              uvFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_batch_uv") {
                  uvFormat = attr.format;
                  break;
                }
                uvOffset += FormatInfos[attr.format].size;
              }
              if (uvFormat) {
                mapBuffer(dataView, (cur, idx) => {
                  cur = repeat$1(cur);
                  const comp = idx === 0 ? 'x' : 'y';
                  return cur * size[comp] + offset[comp];
                }, uvFormat, uvOffset, bundle.view.length, bundle.view.stride, dataView);
              }
              const idxMap = jointIndexMap[i];
              if (!idxMap) {
                continue;
              }
              jointOffset = bundle.view.offset;
              jointFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_joints") {
                  jointFormat = attr.format;
                  break;
                }
                jointOffset += FormatInfos[attr.format].size;
              }
              if (jointFormat) {
                mapBuffer(dataView, cur => idxMap[cur], jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
              }
            }
            this._mesh.merge(newMesh);
          }
          this._onMeshChanged(this._mesh);
          this._updateModels();
        }
        cookTextures(target, prop, passIdx) {
          const texImages = [];
          const texImageRegions = [];
          const texBuffers = [];
          const texBufferRegions = [];
          for (let u = 0; u < this.units.length; u++) {
            const unit = this.units[u];
            if (!unit.material) {
              continue;
            }
            const partial = unit.material.getProperty(prop, passIdx);
            if (partial && partial.image && partial.image.data) {
              const 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;
              const {
                data
              } = partial.image;
              if (!ArrayBuffer.isView(data)) {
                texImages.push(data);
                texImageRegions.push(region);
              } else {
                texBuffers.push(data);
                texBufferRegions.push(region);
              }
            }
          }
          const gfxTex = target.getGFXTexture();
          const {
            device
          } = cclegacy.director.root;
          if (texBuffers.length > 0) {
            device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions);
          }
          if (texImages.length > 0) {
            device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions);
          }
        }
        createTexture(prop) {
          const tex = new Texture2D$1();
          tex.setFilters(2, 2);
          tex.setMipFilter(1);
          tex.reset({
            width: this.atlasSize,
            height: this.atlasSize,
            format: 35
          });
          this._textures[prop] = tex;
          return tex;
        }
        resizeAtlases() {
          for (const prop in this._textures) {
            const tex = this._textures[prop];
            tex.reset({
              width: this.atlasSize,
              height: this.atlasSize,
              format: 35
            });
          }
        }
        _createUnitMesh(unitIdx, mesh) {
          const newMeshStruct = JSON.parse(JSON.stringify(mesh.struct));
          const modifiedBundles = {};
          for (let p = 0; p < mesh.struct.primitives.length; p++) {
            const primitive = mesh.struct.primitives[p];
            let uvOffset = 0;
            let uvFormat = 0;
            let bundleIdx = 0;
            for (; bundleIdx < primitive.vertexBundelIndices.length; bundleIdx++) {
              const bundle = mesh.struct.vertexBundles[primitive.vertexBundelIndices[bundleIdx]];
              uvOffset = bundle.view.offset;
              uvFormat = 0;
              for (let a = 0; a < bundle.attributes.length; a++) {
                const attr = bundle.attributes[a];
                if (attr.name === "a_texCoord") {
                  uvFormat = attr.format;
                  break;
                }
                uvOffset += FormatInfos[attr.format].size;
              }
              if (uvFormat) {
                break;
              }
            }
            if (modifiedBundles[bundleIdx] !== undefined) {
              continue;
            }
            modifiedBundles[bundleIdx] = [uvFormat, uvOffset];
            const 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;
          }
          let totalLength = 0;
          for (let b = 0; b < newMeshStruct.vertexBundles.length; b++) {
            totalLength += newMeshStruct.vertexBundles[b].view.length;
          }
          for (let p = 0; p < newMeshStruct.primitives.length; p++) {
            const pm = newMeshStruct.primitives[p];
            if (pm.indexView) {
              pm.indexView.offset = totalLength;
              totalLength += pm.indexView.length;
            }
          }
          const newMeshData = new Uint8Array(totalLength);
          const oldMeshData = mesh.data;
          const newDataView = new DataView(newMeshData.buffer);
          const oldDataView = new DataView(oldMeshData.buffer);
          const {
            isLittleEndian
          } = cclegacy.sys;
          for (const b in modifiedBundles) {
            const newBundle = newMeshStruct.vertexBundles[b];
            const oldBundle = mesh.struct.vertexBundles[b];
            const [uvFormat, uvOffset] = modifiedBundles[b];
            const uvs = readBuffer(oldDataView, uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride);
            const oldView = oldBundle.view;
            const newView = newBundle.view;
            const oldStride = oldView.stride;
            const newStride = newView.stride;
            let oldOffset = oldView.offset;
            let newOffset = newView.offset;
            for (let j = 0; j < newView.count; j++) {
              const 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 (let k = 0; k < newMeshStruct.primitives.length; k++) {
            const oldPrimitive = mesh.struct.primitives[k];
            const newPrimitive = newMeshStruct.primitives[k];
            if (oldPrimitive.indexView && newPrimitive.indexView) {
              const oldStride = oldPrimitive.indexView.stride;
              const newStride = newPrimitive.indexView.stride;
              let oldOffset = oldPrimitive.indexView.offset;
              let newOffset = newPrimitive.indexView.offset;
              for (let j = 0; j < newPrimitive.indexView.count; j++) {
                const srcIndices = oldMeshData.subarray(oldOffset, oldOffset + oldStride);
                newMeshData.set(srcIndices, newOffset);
                newOffset += newStride;
                oldOffset += oldStride;
              }
            }
          }
          const newMesh = new Mesh();
          newMesh.reset({
            struct: newMeshStruct,
            data: newMeshData
          });
          return newMesh;
        }
      }, (_initializer7$9 = applyDecoratedInitializer(_class5$3.prototype, "atlasSize", [serializable$l], function () {
        return 1024;
      }), _initializer8$9 = applyDecoratedInitializer(_class5$3.prototype, "batchableTextureNames", [_dec8$6, serializable$l], function () {
        return [];
      }), _initializer9$8 = applyDecoratedInitializer(_class5$3.prototype, "units", [_dec9$5, serializable$l], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$3.prototype, "mesh", [override$1], Object.getOwnPropertyDescriptor(_class5$3.prototype, "mesh"), _class5$3.prototype), _applyDecoratedDescriptor(_class5$3.prototype, "skeleton", [override$1], Object.getOwnPropertyDescriptor(_class5$3.prototype, "skeleton"), _class5$3.prototype)), _class5$3)) || _class4$2) || _class4$2);

      cclegacy.SkinningModelComponent = SkinnedMeshRenderer;
      setClassAlias(SkinnedMeshRenderer, 'cc.SkinningModelComponent');
      cclegacy.SkinningModelUnit = SkinnedMeshUnit;
      setClassAlias(SkinnedMeshUnit, 'cc.SkinningModelUnit');
      cclegacy.BatchedSkinningModelComponent = SkinnedMeshBatchRenderer;
      setClassAlias(SkinnedMeshBatchRenderer, 'cc.BatchedSkinningModelComponent');

      var _dec$s, _dec2$p, _class$s, _class2$o, _initializer$n, _initializer2$l, _dec3$n, _dec4$g, _dec5$g, _dec6$a, _class4$1, _class5$2, _initializer3$h, _initializer4$f, _class6$1;
      let Socket = exports("Socket", (_dec$s = ccclass$H('cc.SkeletalAnimation.Socket'), _dec2$p = type$a(Node$1), _dec$s(_class$s = (_class2$o = class Socket {
        constructor(path = '', target = null) {
          this.path = _initializer$n && _initializer$n();
          this.target = _initializer2$l && _initializer2$l();
          this.path = path;
          this.target = target;
        }
      }, (_initializer$n = applyDecoratedInitializer(_class2$o.prototype, "path", [serializable$l], function () {
        return '';
      }), _initializer2$l = applyDecoratedInitializer(_class2$o.prototype, "target", [_dec2$p], function () {
        return null;
      })), _class2$o)) || _class$s));
      setClassAlias(Socket, 'cc.SkeletalAnimationComponent.Socket');
      const m4_1 = new Mat4();
      const m4_2 = new Mat4();
      function collectRecursively(node, prefix = '', out = []) {
        for (let i = 0; i < node.children.length; i++) {
          const child = node.children[i];
          if (!child) {
            continue;
          }
          const path = prefix ? `${prefix}/${child.name}` : child.name;
          out.push(path);
          collectRecursively(child, path, out);
        }
        return out;
      }
      let SkeletalAnimation = (_dec3$n = ccclass$H('cc.SkeletalAnimation'), _dec4$g = executionOrder$1(99), _dec5$g = type$a([Socket]), _dec6$a = type$a([Socket]), _dec3$n(_class4$1 = _dec4$g(_class4$1 = (_class5$2 = (_class6$1 = class SkeletalAnimation extends Animation$2 {
        constructor(...args) {
          super(...args);
          this._useBakedAnimation = _initializer3$h && _initializer3$h();
          this._sockets = _initializer4$f && _initializer4$f();
          this._users = new Set();
          this._currentBakedState = null;
        }
        get sockets() {
          return this._sockets;
        }
        set sockets(val) {
          if (!this._useBakedEffectively) {
            const animMgr = getGlobalAnimationManager();
            animMgr.removeSockets(this.node, this._sockets);
            animMgr.addSockets(this.node, val);
          }
          this._sockets = val;
          this.rebuildSocketAnimations();
        }
        get useBakedAnimation() {
          return this._useBakedAnimation;
        }
        set useBakedAnimation(value) {
          this._useBakedAnimation = value;
          this._applyBakeFlagChange();
        }
        onLoad() {
          super.onLoad();
          const comps = this.node.getComponentsInChildren(SkinnedMeshRenderer);
          for (let i = 0; i < comps.length; ++i) {
            const comp = comps[i];
            if (comp.skinningRoot === this.node) {
              this.notifySkinnedMeshAdded(comp);
            }
          }
        }
        onDestroy() {
          super.onDestroy();
          cclegacy.director.root.dataPoolManager.jointAnimationInfo.destroy(this.node.uuid);
          getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          this._removeAllUsers();
        }
        onEnable() {
          var _this$_currentBakedSt;
          super.onEnable();
          (_this$_currentBakedSt = this._currentBakedState) === null || _this$_currentBakedSt === void 0 ? void 0 : _this$_currentBakedSt.resume();
        }
        onDisable() {
          var _this$_currentBakedSt2;
          super.onDisable();
          (_this$_currentBakedSt2 = this._currentBakedState) === null || _this$_currentBakedSt2 === void 0 ? void 0 : _this$_currentBakedSt2.pause();
        }
        start() {
          this.sockets = this._sockets;
          this._applyBakeFlagChange();
          super.start();
        }
        pause() {
          if (!this._useBakedEffectively) {
            super.pause();
          } else {
            var _this$_currentBakedSt3;
            (_this$_currentBakedSt3 = this._currentBakedState) === null || _this$_currentBakedSt3 === void 0 ? void 0 : _this$_currentBakedSt3.pause();
          }
        }
        resume() {
          if (!this._useBakedEffectively) {
            super.resume();
          } else {
            var _this$_currentBakedSt4;
            (_this$_currentBakedSt4 = this._currentBakedState) === null || _this$_currentBakedSt4 === void 0 ? void 0 : _this$_currentBakedSt4.resume();
          }
        }
        stop() {
          if (!this._useBakedEffectively) {
            super.stop();
          } else if (this._currentBakedState) {
            this._currentBakedState.stop();
            this._currentBakedState = null;
          }
        }
        querySockets() {
          const animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort().reduce((acc, cur) => cur.startsWith(`${acc[acc.length - 1]}/`) ? acc : (acc.push(cur), acc), []) || [];
          if (!animPaths.length) {
            return ['please specify a valid default animation clip first'];
          }
          const out = [];
          for (let i = 0; i < animPaths.length; i++) {
            const path = animPaths[i];
            const node = this.node.getChildByPath(path);
            if (!node) {
              continue;
            }
            out.push(path);
            collectRecursively(node, path, out);
          }
          return out;
        }
        rebuildSocketAnimations() {
          for (const socket of this._sockets) {
            const joint = this.node.getChildByPath(socket.path);
            const {
              target
            } = socket;
            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 (const stateName of Object.keys(this._nameToState)) {
            const state = this._nameToState[stateName];
            state.rebuildSocketCurves(this._sockets);
          }
        }
        createSocket(path) {
          const socket = this._sockets.find(s => s.path === path);
          if (socket) {
            return socket.target;
          }
          const joint = this.node.getChildByPath(path);
          if (!joint) {
            warn('illegal socket path');
            return null;
          }
          const target = new Node$1();
          target.parent = this.node;
          this._sockets.push(new Socket(path, target));
          this.rebuildSocketAnimations();
          return target;
        }
        notifySkinnedMeshAdded(skinnedMeshRenderer) {
          const {
            _useBakedEffectively
          } = this;
          const formerBound = skinnedMeshRenderer.associatedAnimation;
          if (formerBound) {
            formerBound._users.delete(skinnedMeshRenderer);
          }
          skinnedMeshRenderer.associatedAnimation = this;
          skinnedMeshRenderer.setUseBakedAnimation(_useBakedEffectively, true);
          if (_useBakedEffectively) {
            const {
              _currentBakedState: playingState
            } = this;
            if (playingState) {
              skinnedMeshRenderer.uploadAnimation(playingState.clip);
            }
          }
          this._users.add(skinnedMeshRenderer);
        }
        notifySkinnedMeshRemoved(skinnedMeshRenderer) {
          assertIsTrue(skinnedMeshRenderer.associatedAnimation === this || skinnedMeshRenderer.associatedAnimation === null);
          skinnedMeshRenderer.setUseBakedAnimation(false);
          skinnedMeshRenderer.associatedAnimation = null;
          this._users.delete(skinnedMeshRenderer);
        }
        getUsers() {
          return this._users;
        }
        _createState(clip, name) {
          return new SkeletalAnimationState(clip, name);
        }
        _doCreateState(clip, name) {
          const state = super._doCreateState(clip, name);
          state.rebuildSocketCurves(this._sockets);
          return state;
        }
        doPlayOrCrossFade(state, duration) {
          if (this._useBakedEffectively) {
            if (this._currentBakedState) {
              this._currentBakedState.stop();
            }
            const skeletalAnimationState = state;
            this._currentBakedState = skeletalAnimationState;
            skeletalAnimationState.play();
          } else {
            super.doPlayOrCrossFade(state, duration);
          }
        }
        _removeAllUsers() {
          Array.from(this._users).forEach(user => {
            this.notifySkinnedMeshRemoved(user);
          });
        }
        get _useBakedEffectively() {
          {
            return this._useBakedAnimation;
          }
        }
        _applyBakeFlagChange() {
          const useBakedEffectively = this._useBakedEffectively;
          for (const stateName in this._nameToState) {
            const state = this._nameToState[stateName];
            state.setUseBaked(useBakedEffectively);
          }
          this._users.forEach(user => {
            user.setUseBakedAnimation(useBakedEffectively);
          });
          if (useBakedEffectively) {
            getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          } else {
            getGlobalAnimationManager().addSockets(this.node, this._sockets);
            this._currentBakedState = null;
          }
        }
      }, _class6$1.Socket = Socket, _class6$1), (_applyDecoratedDescriptor(_class5$2.prototype, "sockets", [_dec5$g], Object.getOwnPropertyDescriptor(_class5$2.prototype, "sockets"), _class5$2.prototype), _initializer3$h = applyDecoratedInitializer(_class5$2.prototype, "_useBakedAnimation", [serializable$l], function () {
        return true;
      }), _initializer4$f = applyDecoratedInitializer(_class5$2.prototype, "_sockets", [_dec6$a], function () {
        return [];
      })), _class5$2)) || _class4$1) || _class4$1); exports({ SkeletalAnimation: SkeletalAnimation, SkeletalAnimationComponent: SkeletalAnimation });

      cclegacy.SkeletalAnimationComponent = SkeletalAnimation;
      setClassAlias(SkeletalAnimation, 'cc.SkeletalAnimationComponent');

      var spine$1;
      (function (spine, _class) {
        function defineReverseKeyEnum(e) {
          for (var key in e) {
            var value = e[key];
            e[value] = key;
          }
        }
        var e = spine.MixBlend = {
          setup: 0,
          first: 1,
          replace: 2,
          add: 3
        };
        defineReverseKeyEnum(e);
        e = spine.MixDirection = {
          mixIn: 0,
          mixOut: 1
        };
        defineReverseKeyEnum(e);
        e = spine.TimelineType = {
          rotate: 0,
          translate: 1,
          scale: 2,
          shear: 3,
          attachment: 4,
          color: 5,
          deform: 6,
          event: 7,
          drawOrder: 8,
          ikConstraint: 9,
          transformConstraint: 10,
          pathConstraintPosition: 11,
          pathConstraintSpacing: 12,
          pathConstraintMix: 13,
          twoColor: 14
        };
        defineReverseKeyEnum(e);
        e = spine.EventType = {
          start: 0,
          interrupt: 1,
          end: 2,
          dispose: 3,
          complete: 4,
          event: 5
        };
        defineReverseKeyEnum(e);
        e = spine.BlendMode = {
          Normal: 0,
          Additive: 1,
          Multiply: 2,
          Screen: 3
        };
        defineReverseKeyEnum(e);
        e = spine.TransformMode = {
          Normal: 0,
          OnlyTranslation: 1,
          NoRotationOrReflection: 2,
          NoScale: 3,
          NoScaleOrReflection: 4
        };
        defineReverseKeyEnum(e);
        e = spine.PositionMode = {
          Fixed: 0,
          Percent: 1
        };
        defineReverseKeyEnum(e);
        e = spine.SpacingMode = {
          Length: 0,
          Fixed: 1,
          Percent: 2
        };
        defineReverseKeyEnum(e);
        e = spine.RotateMode = {
          Tangent: 0,
          Chain: 1,
          ChainScale: 2
        };
        defineReverseKeyEnum(e);
        e = spine.TextureFilter = {
          Nearest: 9728,
          Linear: 9729,
          MipMap: 9987,
          MipMapNearestNearest: 9984,
          MipMapLinearNearest: 9985,
          MipMapNearestLinear: 9986,
          MipMapLinearLinear: 9987
        };
        defineReverseKeyEnum(e);
        e = spine.TextureWrap = {
          MirroredRepeat: 33648,
          ClampToEdge: 33071,
          Repeat: 10497
        };
        defineReverseKeyEnum(e);
        e = spine.AttachmentType = {
          Region: 0,
          BoundingBox: 1,
          Mesh: 2,
          LinkedMesh: 3,
          Path: 4,
          Point: 5,
          Clipping: 6
        };
        defineReverseKeyEnum(e);
        e = null;
        const PI = 3.1415927;
        const PI2 = PI * 2;
        const radiansToDegrees = 180 / PI;
        const radDeg = radiansToDegrees;
        const degreesToRadians = PI / 180;
        const degRad = degreesToRadians;
        spine.MathUtils = (_class = class MathUtils {
          static clamp(value, min, max) {
            if (value < min) return min;
            if (value > max) return max;
            return value;
          }
          static cosDeg(degrees) {
            return Math.cos(degrees * degRad);
          }
          static sinDeg(degrees) {
            return Math.sin(degrees * degRad);
          }
          static signum(value) {
            return value > 0 ? 1 : value < 0 ? -1 : 0;
          }
          static toInt(x) {
            return x > 0 ? Math.floor(x) : Math.ceil(x);
          }
          static cbrt(x) {
            let y = Math.pow(Math.abs(x), 1 / 3);
            return x < 0 ? -y : y;
          }
          static randomTriangular(min, max) {
            return MathUtils.randomTriangularWith(min, max, (min + max) * 0.5);
          }
          static randomTriangularWith(min, max, mode) {
            let u = Math.random();
            let d = max - min;
            if (u <= (mode - min) / d) return min + Math.sqrt(u * d * (mode - min));
            return max - Math.sqrt((1 - u) * d * (max - mode));
          }
        }, _class.PI = PI, _class.PI2 = PI2, _class.radiansToDegrees = radiansToDegrees, _class.radDeg = radDeg, _class.degreesToRadians = degreesToRadians, _class.degRad = degRad, _class);
      })(spine$1 || (spine$1 = {}));
      var spineLib = spine$1;

      let _listener_ID = 0;
      let _track_ID = 0;
      class TrackEntryListeners {
        constructor() {
          this.start = void 0;
          this.interrupt = void 0;
          this.end = void 0;
          this.dispose = void 0;
          this.complete = void 0;
          this.event = void 0;
        }
        static getListeners(entry, instance) {
          if (!entry.listener) {
            entry.listener = new TrackEntryListeners();
            const id = ++_track_ID;
            instance.setTrackEntryListener(id, entry);
            TrackEntryListeners._trackSet.set(id, entry);
          }
          return entry.listener;
        }
        static emitListener(id, entry, event, eventType) {
          const listener = TrackEntryListeners._listenerSet.get(id);
          if (!listener) return;
          switch (eventType) {
            case spineLib.EventType.event:
              if (listener.event) {
                listener.event(entry, event);
              }
              break;
            case spineLib.EventType.start:
              if (listener.start) {
                listener.start(entry);
              }
              break;
            case spineLib.EventType.interrupt:
              if (listener.interrupt) {
                listener.interrupt(entry);
              }
              break;
            case spineLib.EventType.end:
              if (listener.end) {
                listener.end(entry);
              }
              break;
            case spineLib.EventType.dispose:
              if (listener.dispose) {
                listener.dispose(entry);
              }
              break;
            case spineLib.EventType.complete:
              if (listener.complete) {
                listener.complete(entry);
              }
              break;
            default:
              warn('emitListener doesn\'t handled', eventType);
              break;
          }
        }
        static emitTrackEntryListener(id, entry, event, eventType) {
          const curTrack = this._trackSet.get(id);
          if (!curTrack) return;
          switch (eventType) {
            case spineLib.EventType.start:
              if (curTrack.listener.start) {
                curTrack.listener.start(entry);
              }
              break;
            case spineLib.EventType.interrupt:
              if (curTrack.listener.interrupt) {
                curTrack.listener.interrupt(entry);
              }
              break;
            case spineLib.EventType.end:
              if (curTrack.listener.end) {
                curTrack.listener.end(entry);
              }
              break;
            case spineLib.EventType.dispose:
              if (curTrack.listener.dispose) {
                curTrack.listener.dispose(entry);
              }
              this._trackSet.delete(id);
              curTrack.listener = null;
              break;
            case spineLib.EventType.complete:
              if (curTrack.listener.complete) {
                curTrack.listener.complete(entry);
              }
              break;
            case spineLib.EventType.event:
              if (curTrack.listener.event) {
                curTrack.listener.event(entry, event);
              }
              break;
            default:
              warn('TrackEntry doesn\'t handled', eventType);
              break;
          }
        }
        static addListener(listener) {
          const id = ++_listener_ID;
          TrackEntryListeners._listenerSet.set(id, listener);
          return id;
        }
        static removeListener(id) {
          TrackEntryListeners._listenerSet.delete(id);
        }
      }
      TrackEntryListeners._listenerSet = new Map();
      TrackEntryListeners._trackSet = new Map();
      globalThis.TrackEntryListeners = TrackEntryListeners;

      var _class5$1;
      const MaxCacheTime = 30;
      const FrameTime = 1 / 60;
      const _useTint$1 = true;
      getAttributeStride(vfmtPosUvColor4B);
      const _byteStrideTwoColor$1 = getAttributeStride(vfmtPosUvTwoColor4B);
      class FrameBoneInfo {
        constructor() {
          this.a = 0;
          this.b = 0;
          this.c = 0;
          this.d = 0;
          this.worldX = 0;
          this.worldY = 0;
        }
      }
      class SpineModel {
        constructor() {
          this.vCount = 0;
          this.iCount = 0;
          this.vData = null;
          this.iData = null;
          this.meshes = [];
        }
      }
      class SpineDrawItem {
        constructor() {
          this.iCount = 0;
          this.blendMode = 0;
          this.textureID = 0;
        }
      }
      class AnimationCache {
        constructor(data) {
          this._instance = null;
          this._state = null;
          this._skeletonData = null;
          this._skeleton = null;
          this._privateMode = false;
          this._curIndex = -1;
          this._isCompleted = false;
          this._maxFrameIdex = 0;
          this._frameIdx = -1;
          this._inited = false;
          this._invalid = true;
          this._enableCacheAttachedInfo = false;
          this._skeletonInfo = null;
          this._animationName = null;
          this.isCompleted = false;
          this.totalTime = 0;
          this.frames = [];
          this._privateMode = false;
          this._inited = false;
          this._invalid = true;
          this._instance = new spineLib.SkeletonInstance();
          this._instance.isCache = true;
          this._skeletonData = data;
          this._skeleton = this._instance.initSkeleton(data);
          this._instance.setUseTint(_useTint$1);
        }
        init(skeletonInfo, animationName) {
          this._inited = true;
          this._animationName = animationName;
          this._skeletonInfo = skeletonInfo;
        }
        get skeleton() {
          return this._skeleton;
        }
        setSkin(skinName) {
          if (this._skeleton) this._skeleton.setSkinByName(skinName);
          this._instance.setSkin(skinName);
        }
        setAnimation(animationName) {
          const animations = this._skeletonData.animations;
          let animation = null;
          animations.forEach(element => {
            if (element.name === animationName) {
              animation = element;
            }
          });
          if (!animation) {
            warn(`find no animation named ${animationName} !!!`);
            return;
          }
          this._maxFrameIdex = Math.floor(animation.duration / FrameTime);
          if (this._maxFrameIdex <= 0) this._maxFrameIdex = 1;
          this._instance.setAnimation(0, animationName, false);
        }
        updateToFrame(frameIdx) {
          if (!this._inited) return;
          this.begin();
          if (!this.needToUpdate(frameIdx)) return;
          do {
            this._frameIdx++;
            this.totalTime += FrameTime;
            this._instance.updateAnimation(FrameTime);
            const model = this._instance.updateRenderData();
            this.updateRenderData(this._frameIdx, model);
            if (this._frameIdx >= this._maxFrameIdex) {
              this.isCompleted = true;
            }
          } while (this.needToUpdate(frameIdx));
        }
        getFrame(frameIdx) {
          const index = frameIdx % this._maxFrameIdex;
          return this.frames[index];
        }
        invalidAnimationFrames() {
          this._curIndex = -1;
          this._isCompleted = false;
          this.frames.length = 0;
        }
        updateRenderData(index, model) {
          const vc = model.vCount;
          const ic = model.iCount;
          const floatStride = (_byteStrideTwoColor$1 ) / 4;
          const vUint8Buf = new Uint8Array(4 * floatStride * vc);
          const iUint16Buf = new Uint16Array(ic);
          const HEAPU8 = spineLib.wasmUtil.wasm.HEAPU8;
          const vPtr = model.vPtr;
          const vLength = vc * 4 * floatStride;
          vUint8Buf.set(HEAPU8.subarray(vPtr, vPtr + vLength));
          const iPtr = model.iPtr;
          const iLength = 2 * ic;
          const iUint8Buf = new Uint8Array(iUint16Buf.buffer);
          iUint8Buf.set(HEAPU8.subarray(iPtr, iPtr + iLength));
          const modelData = new SpineModel();
          modelData.vCount = vc;
          modelData.iCount = ic;
          modelData.vData = vUint8Buf;
          modelData.iData = iUint16Buf;
          const data = model.getData();
          const count = data.size();
          for (let i = 0; i < count; i += 6) {
            const meshData = new SpineDrawItem();
            meshData.iCount = data.get(i + 3);
            meshData.blendMode = data.get(i + 4);
            meshData.textureID = data.get(i + 5);
            modelData.meshes.push(meshData);
          }
          const bones = this._skeleton.bones;
          const boneInfosArray = [];
          bones.forEach(bone => {
            const boneInfo = new FrameBoneInfo();
            boneInfo.a = bone.a;
            boneInfo.b = bone.b;
            boneInfo.c = bone.c;
            boneInfo.d = bone.d;
            boneInfo.worldX = bone.worldX;
            boneInfo.worldY = bone.worldY;
            boneInfosArray.push(boneInfo);
          });
          this.frames[index] = {
            model: modelData,
            boneInfos: boneInfosArray
          };
        }
        begin() {
          if (!this._invalid) return;
          const skeletonInfo = this._skeletonInfo;
          const preAnimationCache = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.curAnimationCache;
          if (preAnimationCache && preAnimationCache !== this) {
            if (this._privateMode) {
              preAnimationCache.invalidAllFrame();
            } else {
              preAnimationCache.updateToFrame(0);
            }
          }
          const listener = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.listener;
          this._instance.setAnimation(0, this._animationName, false);
          this.bind(listener);
          skeletonInfo.curAnimationCache = this;
          this._frameIdx = -1;
          this.isCompleted = false;
          this.totalTime = 0;
          this._invalid = false;
        }
        end() {
          if (!this.needToUpdate()) {
            this._skeletonInfo.curAnimationCache = null;
            this.frames.length = this._frameIdx + 1;
            this.isCompleted = true;
            this.unbind(this._skeletonInfo.listener);
          }
        }
        bind(listener) {
          const completeHandle = entry => {
            if (entry && entry.animation.name === this._animationName) {
              this.isCompleted = true;
            }
          };
          listener.complete = completeHandle;
        }
        unbind(listener) {
          listener.complete = null;
        }
        needToUpdate(toFrameIdx) {
          return !this.isCompleted && this.totalTime < MaxCacheTime && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
        }
        isInited() {
          return this._inited;
        }
        isInvalid() {
          return this._invalid;
        }
        invalidAllFrame() {
          this.isCompleted = false;
          this._invalid = true;
        }
        enableCacheAttachedInfo() {
          if (!this._enableCacheAttachedInfo) {
            this._enableCacheAttachedInfo = true;
            this.invalidAllFrame();
          }
        }
        clear() {
          this._inited = false;
          this.invalidAllFrame();
        }
        destroy() {
          if (this._instance) {
            this._instance.destroy();
            this._instance = null;
          }
        }
      }
      class SkeletonCache {
        constructor() {
          this._privateMode = void 0;
          this._skeletonCache = void 0;
          this._animationPool = void 0;
          this._sharedCacheMap = new Map();
          this._privateMode = false;
          this._animationPool = {};
          this._skeletonCache = {};
        }
        enablePrivateMode() {
          this._privateMode = true;
        }
        clear() {
          this._animationPool = {};
          this._skeletonCache = {};
        }
        invalidAnimationCache(uuid) {
          const skeletonInfo = this._skeletonCache[uuid];
          const skeleton = skeletonInfo && skeletonInfo.skeleton;
          if (!skeleton) return;
          const animationsCache = skeletonInfo.animationsCache;
          for (const aniKey in animationsCache) {
            const animationCache = animationsCache[aniKey];
            animationCache.invalidAllFrame();
          }
        }
        destroySkeleton(assetUuid) {
          if (!this._privateMode) {
            let refCount = this._sharedCacheMap.get(assetUuid);
            if (refCount) {
              refCount -= 1;
              if (refCount > 0) {
                this._sharedCacheMap.set(assetUuid, refCount);
                return;
              }
              this._sharedCacheMap.delete(assetUuid);
            }
          }
          const skeletonInfo = this._skeletonCache[assetUuid];
          if (!skeletonInfo) return;
          const sharedOperate = (aniKey, animationCache) => {
            this._animationPool[`${assetUuid}#${aniKey}`] = animationCache;
            animationCache.clear();
          };
          const privateOperate = (aniKey, animationCache) => {
            animationCache.destroy();
          };
          const operate = this._privateMode ? privateOperate : sharedOperate;
          const animationsCache = skeletonInfo.animationsCache;
          for (const aniKey in animationsCache) {
            const animationCache = animationsCache[aniKey];
            if (!animationCache) continue;
            operate(aniKey, animationCache);
          }
          if (skeletonInfo.skeleton) {
            spineLib.wasmUtil.destroySpineSkeleton(skeletonInfo.skeleton);
          }
          delete this._skeletonCache[assetUuid];
        }
        createSkeletonInfo(skeletonAsset) {
          const uuid = skeletonAsset.uuid;
          const runtimeData = skeletonAsset.getRuntimeData();
          if (!this._privateMode) {
            let refCount = this._sharedCacheMap.get(uuid);
            if (!refCount) {
              refCount = 1;
            } else {
              refCount += 1;
            }
            this._sharedCacheMap.set(uuid, refCount);
          }
          if (this._skeletonCache[uuid]) {
            return this._skeletonCache[uuid];
          }
          const skeleton = new spineLib.Skeleton(runtimeData);
          const clipper = null;
          const state = null;
          const listener = new TrackEntryListeners();
          const skeletonInfo = this._skeletonCache[uuid] = {
            skeleton,
            clipper,
            state,
            listener,
            animationsCache: {},
            curAnimationCache: null,
            assetUUID: uuid
          };
          return skeletonInfo;
        }
        getSkeletonInfo(skeletonAsset) {
          const uuid = skeletonAsset.uuid;
          return this._skeletonCache[uuid];
        }
        getAnimationCache(uuid, animationName) {
          const skeletonInfo = this._skeletonCache[uuid];
          if (!skeletonInfo) return null;
          const animationsCache = skeletonInfo.animationsCache;
          return animationsCache[animationName];
        }
        initAnimationCache(uuid, data, animationName) {
          const spData = data.getRuntimeData();
          if (!spData) return null;
          const skeletonInfo = this._skeletonCache[uuid];
          const skeleton = skeletonInfo && skeletonInfo.skeleton;
          if (!skeleton) return null;
          const animationsCache = skeletonInfo.animationsCache;
          let animationCache = animationsCache[animationName];
          if (!animationCache) {
            const poolKey = `${uuid}#${animationName}`;
            animationCache = this._animationPool[poolKey];
            if (animationCache) {
              delete this._animationPool[poolKey];
            } else {
              animationCache = new AnimationCache(spData);
              animationCache._privateMode = this._privateMode;
            }
            animationCache.init(skeletonInfo, animationName);
            animationsCache[animationName] = animationCache;
          }
          animationCache.init(skeletonInfo, animationName);
          animationCache.setAnimation(animationName);
          return animationCache;
        }
        destroyCachedAnimations(uuid) {
          if (uuid) {
            const animationPool = this._animationPool;
            for (const key in animationPool) {
              if (key.includes(uuid)) {
                animationPool[key].destroy();
                delete animationPool[key];
              }
            }
            let skeletonInfo = this._skeletonCache[uuid];
            const skeleton = skeletonInfo && skeletonInfo.skeleton;
            if (skeleton) {
              spineLib.wasmUtil.destroySpineSkeleton(skeleton);
            }
            if (skeletonInfo) {
              delete this._skeletonCache[uuid];
            }
          } else {
            const animationPool = this._animationPool;
            for (const key in animationPool) {
              animationPool[key].destroy();
              delete animationPool[key];
            }
          }
        }
      }
      _class5$1 = SkeletonCache;
      SkeletonCache.FrameTime = FrameTime;
      SkeletonCache.sharedCache = new _class5$1();

      var _dec$r, _dec2$o, _dec3$m, _class$r, _class2$n, _initializer$m, _initializer2$k, _initializer3$g, _initializer4$e, _initializer5$c;
      let SkeletonData = (_dec$r = ccclass$H('sp.SkeletonData'), _dec2$o = type$a([Texture2D$1]), _dec3$m = type$a([CCString]), _dec$r(_class$r = (_class2$n = class SkeletonData extends Asset {
        get skeletonJsonStr() {
          if (this._skeletonJson) {
            return JSON.stringify(this._skeletonJson);
          }
          return '';
        }
        get skeletonJson() {
          return this._skeletonJson;
        }
        set skeletonJson(value) {
          this.reset();
          if (typeof value === 'string') {
            this._skeletonJson = JSON.parse(value);
          } else {
            this._skeletonJson = value;
          }
          if (!this._uuid && value.skeleton) {
            this._uuid = value.skeleton.hash;
          }
        }
        get atlasText() {
          return this._atlasText;
        }
        set atlasText(value) {
          this._atlasText = value;
          this.reset();
        }
        get _nativeAsset() {
          return this._buffer;
        }
        set _nativeAsset(bin) {
          this._buffer = bin;
          this.reset();
        }
        constructor() {
          super();
          this._skeletonJson = _initializer$m && _initializer$m();
          this.textures = _initializer2$k && _initializer2$k();
          this.textureNames = _initializer3$g && _initializer3$g();
          this.scale = _initializer4$e && _initializer4$e();
          this._atlasText = _initializer5$c && _initializer5$c();
          this._buffer = void 0;
          this._skeletonCache = null;
          this._skinsEnum = null;
          this._animsEnum = null;
          this.reset();
        }
        createNode(callback) {
          const node = new Node$1(this.name);
          const skeleton = node.addComponent('cc.Skeleton');
          skeleton.skeletonData = this;
          return callback(null, node);
        }
        reset() {
          this._skeletonCache = null;
        }
        resetEnums() {
        }
        getRuntimeData(quiet) {
          if (this._skeletonCache) {
            return this._skeletonCache;
          }
          if (!(this.textures && this.textures.length > 0) && this.textureNames && this.textureNames.length > 0) {
            if (!quiet) {
              error(`${this.name} no textures found!`);
            }
            return null;
          }
          const uuid = this.mergedUUID();
          const spData = spineLib.wasmUtil.querySpineSkeletonDataByUUID(uuid);
          if (spData) {
            this._skeletonCache = spData;
          } else if (this._skeletonJson) {
            this._skeletonCache = spineLib.wasmUtil.createSpineSkeletonDataWithJson(this.skeletonJsonStr, this._atlasText);
            spineLib.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, uuid);
          } else {
            const rawData = new Uint8Array(this._nativeAsset);
            const byteSize = rawData.length;
            const ptr = spineLib.wasmUtil.queryStoreMemory(byteSize);
            const wasmMem = spineLib.wasmUtil.wasm.HEAPU8.subarray(ptr, ptr + byteSize);
            wasmMem.set(rawData);
            this._skeletonCache = spineLib.wasmUtil.createSpineSkeletonDataWithBinary(byteSize, this._atlasText);
            spineLib.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, uuid);
          }
          return this._skeletonCache;
        }
        getSkinsEnum() {
          if (this._skinsEnum) {
            return this._skinsEnum;
          }
          const sd = this.getRuntimeData(true);
          if (sd) {
            const skins = sd.skins;
            const enumDef = {};
            for (let i = 0; i < skins.length; i++) {
              const name = skins[i].name;
              enumDef[name] = i;
            }
            return this._skinsEnum = Enum(enumDef);
          }
          return null;
        }
        getAnimsEnum() {
          if (this._animsEnum && Object.keys(this._animsEnum).length > 1) {
            return this._animsEnum;
          }
          const sd = this.getRuntimeData(true);
          if (sd) {
            const enumDef = {
              '<None>': 0
            };
            const anims = sd.animations;
            for (let i = 0; i < anims.length; i++) {
              const name = anims[i].name;
              enumDef[name] = i + 1;
            }
            return this._animsEnum = Enum(enumDef);
          }
          return null;
        }
        mergedUUID() {
          return this._uuid + murmurhash2_32_gc(this._atlasText, 668).toString();
        }
        destroy() {
          SkeletonCache.sharedCache.destroyCachedAnimations(this._uuid);
          spineLib.wasmUtil.destroySpineSkeletonDataWithUUID(this.mergedUUID());
          return super.destroy();
        }
      }, (_initializer$m = applyDecoratedInitializer(_class2$n.prototype, "_skeletonJson", [serializable$l], function () {
        return null;
      }), _initializer2$k = applyDecoratedInitializer(_class2$n.prototype, "textures", [serializable$l, _dec2$o], function () {
        return [];
      }), _initializer3$g = applyDecoratedInitializer(_class2$n.prototype, "textureNames", [serializable$l, _dec3$m], function () {
        return [];
      }), _initializer4$e = applyDecoratedInitializer(_class2$n.prototype, "scale", [serializable$l], function () {
        return 1;
      }), _initializer5$c = applyDecoratedInitializer(_class2$n.prototype, "_atlasText", [serializable$l], function () {
        return '';
      })), _class2$n)) || _class$r);
      legacyCC.internal.SpineSkeletonData = SkeletonData;

      class SkeletonSystem extends System {
        constructor() {
          super();
          this._skeletons = new Set();
        }
        static getInstance() {
          if (!SkeletonSystem._instance) {
            SkeletonSystem._instance = new SkeletonSystem();
            director.registerSystem(SkeletonSystem.ID, SkeletonSystem._instance, System.Priority.HIGH);
          }
          return SkeletonSystem._instance;
        }
        add(skeleton) {
          if (!skeleton) return;
          if (!this._skeletons.has(skeleton)) {
            this._skeletons.add(skeleton);
          }
        }
        remove(skeleton) {
          if (!skeleton) return;
          if (this._skeletons.has(skeleton)) {
            this._skeletons.delete(skeleton);
          }
        }
        postUpdate(dt) {
          if (!this._skeletons) {
            return;
          }
          this._skeletons.forEach(skeleton => {
            skeleton.updateAnimation(dt);
          });
        }
        prepareRenderData() {
          if (!this._skeletons) {
            return;
          }
          this._skeletons.forEach(skeleton => {
            skeleton.markForUpdateRenderData();
          });
        }
      }
      SkeletonSystem.ID = 'SKELETON';
      SkeletonSystem._instance = void 0;
      legacyCC.internal.SpineSkeletonSystem = SkeletonSystem;

      const tempMat4 = new Mat4();
      class AttachUtil {
        constructor() {
          this._isInitialized = false;
          this._skeletonBones = null;
          this._socketNodes = null;
          this._keysToDelete = [];
          this._isInitialized = false;
        }
        init(skeletonComp) {
          var _skeletonComp$socketN;
          this._isInitialized = false;
          if (!skeletonComp || ((_skeletonComp$socketN = skeletonComp.socketNodes) === null || _skeletonComp$socketN === void 0 ? void 0 : _skeletonComp$socketN.size) === 0) return;
          this._skeletonBones = skeletonComp._skeleton.bones;
          if (!this._skeletonBones || this._skeletonBones.length < 1) return;
          this._socketNodes = skeletonComp.socketNodes;
          if (!this._socketNodes || this._socketNodes.size <= 0) return;
          this._isInitialized = true;
          this._syncAttachedNode();
        }
        updateSkeletonBones(bones) {
          this._skeletonBones = bones;
        }
        reset() {
          this._isInitialized = false;
          this._skeletonBones = null;
          this._socketNodes = null;
          this._keysToDelete.length = 0;
        }
        _syncAttachedNode() {
          if (!this._isInitialized) return;
          const socketNodes = this._socketNodes;
          for (const [boneIdx, boneNode] of socketNodes) {
            if (!boneNode || !boneNode.isValid) {
              this._keysToDelete.push(boneIdx);
              continue;
            }
            const bone = this._skeletonBones[boneIdx];
            if (bone) this.matrixHandle(boneNode, bone);
          }
          if (this._keysToDelete.length <= 0) return;
          for (const boneIdx of this._keysToDelete) {
            socketNodes.delete(boneIdx);
          }
          this._keysToDelete.length = 0;
        }
        matrixHandle(node, bone) {
          const tm = tempMat4;
          tm.m00 = bone.a;
          tm.m01 = bone.c;
          tm.m04 = bone.b;
          tm.m05 = bone.d;
          tm.m12 = bone.worldX;
          tm.m13 = bone.worldY;
          node.matrix = tempMat4;
        }
      }

      var _dec$q, _dec2$n, _class$q, _class2$m, _initializer$l, _initializer2$j, _dec3$l, _dec4$f, _dec5$f, _dec6$9, _dec7$7, _dec8$5, _dec9$4, _class4, _class5, _initializer3$f, _initializer4$d, _initializer5$b, _initializer6$8, _initializer7$8, _initializer8$8, _initializer9$7, _initializer10$7, _initializer11$7, _initializer12$6, _initializer13$4, _initializer14$3, _initializer15$2, _initializer16$2, _class6;
      const CUSTOM_SLOT_TEXTURE_BEGIN = 10000;
      let _slotTextureID = CUSTOM_SLOT_TEXTURE_BEGIN;
      const timeScale = 1.0;
      const SpineAnimationCacheMode = {
        "UNSET": -1,
        "REALTIME": 0,
        "SHARED_CACHE": 1,
        "PRIVATE_CACHE": 2
      };
      ccenum(SpineAnimationCacheMode);
      const AnimationCacheMode = SpineAnimationCacheMode;
      const DefaultSkinsEnum = {
        "default": 0
      };
      ccenum(DefaultSkinsEnum);
      const SpineDefaultAnimsEnum = {
        "<None>": 0
      };
      ccenum(SpineDefaultAnimsEnum);
      const DefaultAnimsEnum = SpineDefaultAnimsEnum;
      const SpineMaterialType = {
        "COLORED_TEXTURED": 0,
        "TWO_COLORED": 1
      };
      let SpineSocket = (_dec$q = ccclass$H('sp.Skeleton.SpineSocket'), _dec2$n = type$a(Node$1), _dec$q(_class$q = (_class2$m = class SpineSocket {
        constructor(path = '', target = null) {
          this.path = _initializer$l && _initializer$l();
          this.target = _initializer2$j && _initializer2$j();
          this.path = path;
          this.target = target;
        }
      }, (_initializer$l = applyDecoratedInitializer(_class2$m.prototype, "path", [serializable$l], function () {
        return '';
      }), _initializer2$j = applyDecoratedInitializer(_class2$m.prototype, "target", [_dec2$n, serializable$l], function () {
        return null;
      })), _class2$m)) || _class$q);
      setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket');
      let Skeleton = (_dec3$l = ccclass$H('sp.Skeleton'), _dec4$f = type$a(SkeletonData), _dec5$f = type$a(DefaultSkinsEnum), _dec6$9 = type$a(SpineDefaultAnimsEnum), _dec7$7 = type$a(SpineAnimationCacheMode), _dec8$5 = type$a([SpineSocket]), _dec9$4 = type$a(Material$1), _dec3$l(_class4 = (_class5 = (_class6 = class Skeleton extends UIRenderer {
        constructor() {
          super();
          this._skeletonData = _initializer3$f && _initializer3$f();
          this.defaultSkin = _initializer4$d && _initializer4$d();
          this.defaultAnimation = _initializer5$b && _initializer5$b();
          this._premultipliedAlpha = _initializer6$8 && _initializer6$8();
          this._timeScale = _initializer7$8 && _initializer7$8();
          this._preCacheMode = _initializer8$8 && _initializer8$8();
          this._cacheMode = _initializer9$7 && _initializer9$7();
          this._sockets = _initializer10$7 && _initializer10$7();
          this._useTint = _initializer11$7 && _initializer11$7();
          this._debugMesh = _initializer12$6 && _initializer12$6();
          this._debugBones = _initializer13$4 && _initializer13$4();
          this._debugSlots = _initializer14$3 && _initializer14$3();
          this._enableBatch = _initializer15$2 && _initializer15$2();
          this._runtimeData = null;
          this._skeleton = null;
          this._instance = null;
          this._state = null;
          this._textures = [];
          this._skeletonInfo = null;
          this._animationName = '';
          this._skinName = '';
          this._drawList = new RecyclePool(() => ({
            material: null,
            texture: null,
            indexOffset: 0,
            indexCount: 0
          }), 1);
          this._materialCache = {};
          this.paused = false;
          this._enumSkins = Enum({});
          this._enumAnimations = Enum({});
          this.attachUtil = void 0;
          this._socketNodes = new Map();
          this._cachedSockets = new Map();
          this._startEntry = void 0;
          this._endEntry = void 0;
          this._paused = false;
          this._accTime = 0;
          this._playCount = 0;
          this._skeletonCache = null;
          this._animCache = null;
          this._animationQueue = [];
          this._headAniInfo = null;
          this._isAniComplete = true;
          this._playTimes = 0;
          this._curFrame = null;
          this._needUpdateSkeltonData = true;
          this._listener = null;
          this._debugRenderer = null;
          this._startSlotIndex = void 0;
          this._endSlotIndex = void 0;
          this._slotTextures = null;
          this._vLength = 0;
          this._vBuffer = null;
          this._iLength = 0;
          this._iBuffer = null;
          this._model = void 0;
          this._tempColor = {
            r: 0,
            g: 0,
            b: 0,
            a: 0
          };
          this._eventListenerID = -1;
          this.loop = _initializer16$2 && _initializer16$2();
          this._useVertexOpacity = true;
          this._startEntry = {
            animation: {
              name: ''
            },
            trackIndex: 0
          };
          this._endEntry = {
            animation: {
              name: ''
            },
            trackIndex: 0
          };
          this._startSlotIndex = -1;
          this._endSlotIndex = -1;
          this.attachUtil = new AttachUtil();
        }
        get drawList() {
          return this._drawList;
        }
        get skeletonData() {
          return this._skeletonData;
        }
        set skeletonData(value) {
          if (value) value.resetEnums();
          if (this._skeletonData !== value) {
            this.destroyRenderData();
            this._skeletonData = value;
            this.defaultSkin = '';
            this.defaultAnimation = '';
            this._animationName = '';
            this._skinName = '';
            this._updateSkeletonData();
            this._updateUITransform();
          }
        }
        get _defaultSkinIndex() {
          if (this.skeletonData) {
            const skinsEnum = this.skeletonData.getSkinsEnum();
            if (skinsEnum) {
              if (this.defaultSkin === '') {
                if (skinsEnum.hasOwnProperty(0)) {
                  this._defaultSkinIndex = 0;
                  return 0;
                }
              } else {
                const skinIndex = skinsEnum[this.defaultSkin];
                if (skinIndex !== undefined) {
                  return skinIndex;
                }
              }
            }
          }
          return 0;
        }
        set _defaultSkinIndex(value) {
          let skinsEnum;
          if (this.skeletonData) {
            skinsEnum = this.skeletonData.getSkinsEnum();
          }
          if (!skinsEnum) {
            error(`${this.name} skin enums are invalid`);
            return;
          }
          const skinName = skinsEnum[value];
          if (skinName !== undefined) {
            this.defaultSkin = String(skinName);
            this.setSkin(this.defaultSkin);
            this._refreshInspector();
            this.markForUpdateRenderData();
          } else {
            error(`${this.name} skin enums are invalid`);
          }
        }
        get _animationIndex() {
          const animationName = this.animation;
          if (this.skeletonData) {
            if (animationName) {
              const animsEnum = this.skeletonData.getAnimsEnum();
              if (animsEnum) {
                const animIndex = animsEnum[animationName];
                if (animIndex !== undefined) {
                  return animIndex;
                }
              }
            } else {
              this._refreshInspector();
            }
          }
          return 0;
        }
        set _animationIndex(value) {
          let animsEnum;
          if (this.skeletonData) {
            animsEnum = this.skeletonData.getAnimsEnum();
          }
          if (!animsEnum) {
            error(`${this.name} animation enums are invalid`);
            return;
          }
          const animName = String(animsEnum[value]);
          if (animName !== undefined) {
            this.animation = animName;
            {
              this.animation = animName;
            }
          } else {
            error(`${this.name} animation enums are invalid`);
          }
        }
        get defaultCacheMode() {
          return this._cacheMode;
        }
        set defaultCacheMode(mode) {
          this._cacheMode = mode;
          this.setAnimationCacheMode(this._cacheMode);
        }
        get premultipliedAlpha() {
          return this._premultipliedAlpha;
        }
        set premultipliedAlpha(v) {
          if (v !== this._premultipliedAlpha) {
            this._premultipliedAlpha = v;
            this._instance.setPremultipliedAlpha(v);
            this.markForUpdateRenderData();
          }
        }
        get timeScale() {
          return this._timeScale;
        }
        set timeScale(value) {
          if (value !== this._timeScale) {
            this._timeScale = value;
            if (this._instance) {
              this._instance.dtRate = this._timeScale * timeScale;
            }
          }
        }
        get useTint() {
          return this._useTint;
        }
        set useTint(value) {
          if (value !== this._useTint) {
            this._useTint = value;
            this._updateUseTint();
          }
        }
        get enableBatch() {
          return this._enableBatch;
        }
        set enableBatch(value) {
          if (value !== this._enableBatch) {
            this._enableBatch = value;
            this._updateBatch();
          }
        }
        get sockets() {
          return this._sockets;
        }
        set sockets(val) {
          this._sockets = val;
          this._updateSocketBindings();
          this.attachUtil.init(this);
        }
        get debugSlots() {
          return this._debugSlots;
        }
        set debugSlots(v) {
          if (v !== this._debugSlots) {
            this._debugSlots = v;
            this._updateDebugDraw();
            this.markForUpdateRenderData();
          }
        }
        get debugBones() {
          return this._debugBones;
        }
        set debugBones(v) {
          if (v !== this._debugBones) {
            this._debugBones = v;
            this._updateDebugDraw();
            this.markForUpdateRenderData();
          }
        }
        get debugMesh() {
          return this._debugMesh;
        }
        set debugMesh(value) {
          if (value !== this._debugMesh) {
            this._debugMesh = value;
            this._updateDebugDraw();
            this.markForUpdateRenderData();
          }
        }
        get socketNodes() {
          return this._socketNodes;
        }
        get animation() {
          return this._animationName;
        }
        set animation(value) {
          if (value) {
            this.setAnimation(0, value, this.loop);
          } else {
            this.clearAnimation(0);
          }
        }
        get customMaterial() {
          return this._customMaterial;
        }
        set customMaterial(val) {
          this._customMaterial = val;
          this.updateMaterial();
          this.markForUpdateRenderData();
        }
        __preload() {
          super.__preload();
          this._updateSkeletonData();
          this._updateDebugDraw();
        }
        onRestore() {
          this.updateMaterial();
          this.markForUpdateRenderData();
        }
        getState() {
          return this._state;
        }
        onEnable() {
          super.onEnable();
          if (this._instance) {
            this._instance.enable = true;
          }
          this._flushAssembler();
          SkeletonSystem.getInstance().add(this);
        }
        onDisable() {
          super.onDisable();
          if (this._instance) {
            this._instance.enable = false;
          }
          SkeletonSystem.getInstance().remove(this);
        }
        onDestroy() {
          var _this$_slotTextures;
          if (this._eventListenerID > 0) {
            TrackEntryListeners.removeListener(this._eventListenerID);
            this._eventListenerID = -1;
          }
          this._drawList.destroy();
          this.destroyRenderData();
          this._cleanMaterialCache();
          this._vBuffer = null;
          this._iBuffer = null;
          this.attachUtil.reset();
          (_this$_slotTextures = this._slotTextures) === null || _this$_slotTextures === void 0 ? void 0 : _this$_slotTextures.clear();
          this._slotTextures = null;
          this._cachedSockets.clear();
          this._socketNodes.clear();
          this._animCache = null;
          SkeletonSystem.getInstance().remove(this);
          this._destroySkeletonInfo(this._skeletonCache);
          this._skeletonCache = null;
          super.onDestroy();
        }
        clearAnimation(trackIndex) {
          if (!this.isAnimationCached()) {
            this.clearTrack(trackIndex || 0);
            this.setToSetupPose();
          }
        }
        clearAnimations() {
          if (!this.isAnimationCached()) {
            this.clearTracks();
            this.setToSetupPose();
          }
        }
        _updateSkeletonData() {
          const skeletonData = this._skeletonData;
          if (!skeletonData) {
            this._runtimeData = null;
            this._state = null;
            this._skeleton = null;
            this._textures = [];
            this._refreshInspector();
            return;
          }
          if (this._instance) {
            this._instance.dtRate = this._timeScale * timeScale;
          }
          this._needUpdateSkeltonData = false;
          this._runtimeData = skeletonData.getRuntimeData();
          if (!this._runtimeData) return;
          this.setSkeletonData(this._runtimeData);
          this._textures = skeletonData.textures;
          this._refreshInspector();
          if (this.defaultAnimation) this.animation = this.defaultAnimation.toString();
          if (this.defaultSkin && this.defaultSkin !== '') this.setSkin(this.defaultSkin);
          this._updateUseTint();
          this._indexBoneSockets();
          this._updateSocketBindings();
          this.attachUtil.init(this);
          this._preCacheMode = this._cacheMode;
        }
        setSkeletonData(skeletonData) {
          {
            const preSkeletonCache = this._skeletonCache;
            if (this._cacheMode === 1) {
              this._skeletonCache = SkeletonCache.sharedCache;
            } else if (this._cacheMode === 2) {
              this._skeletonCache = new SkeletonCache();
              this._skeletonCache.enablePrivateMode();
            } else {
              this._skeletonCache = null;
            }
            if (preSkeletonCache !== this._skeletonCache) {
              this._destroySkeletonInfo(preSkeletonCache);
            }
          }
          if (this.isAnimationCached()) {
            if (this.debugBones || this.debugSlots) {
              warn('Debug bones or slots is invalid in cached mode');
            }
            const skeletonInfo = this._skeletonCache.getSkeletonInfo(this._skeletonData);
            if (this._skeletonInfo !== skeletonInfo) {
              this._destroySkeletonInfo(this._skeletonCache);
              this._skeletonInfo = this._skeletonCache.createSkeletonInfo(this._skeletonData);
            }
            if (this._skeletonInfo) {
              this._skeleton = this._skeletonInfo.skeleton;
            }
          } else {
            this._skeleton = this._instance.initSkeleton(skeletonData);
            this._state = this._instance.getAnimationState();
            this._instance.setPremultipliedAlpha(this._premultipliedAlpha);
          }
          this._flushAssembler();
        }
        setSlotsRange(startSlotIndex, endSlotIndex) {
          if (this.isAnimationCached()) {
            warn('Slots visible range can not be modified in cached mode.');
          } else {
            this._startSlotIndex = startSlotIndex;
            this._endSlotIndex = endSlotIndex;
          }
        }
        getAttachment(slotName, attachmentName) {
          if (this._skeleton) {
            return this._skeleton.getAttachmentByName(slotName, attachmentName);
          }
          return null;
        }
        setAttachment(slotName, attachmentName) {
          if (this._skeleton) {
            this._skeleton.setAttachment(slotName, attachmentName);
          }
          this.invalidAnimationCache();
        }
        getTextureAtlas(regionAttachment) {
          return regionAttachment.region;
        }
        setAnimation(trackIndex, name, loop) {
          if (!(typeof name === 'string')) {
            logID(7511);
            return null;
          }
          const skeleton = this._skeleton;
          const animation = skeleton ? skeleton.data.findAnimation(name) : null;
          if (!animation) {
            logID(7509, name);
            return null;
          }
          let trackEntry = null;
          if (loop === undefined) loop = true;
          this._playTimes = loop ? 0 : 1;
          if (this.isAnimationCached()) {
            if (trackIndex !== 0) {
              warn('Track index can not greater than 0 in cached mode.');
            }
            if (!this._skeletonCache) return null;
            let cache = this._skeletonCache.getAnimationCache(this._skeletonData.uuid, name);
            if (!cache) {
              cache = this._skeletonCache.initAnimationCache(this.skeletonData.uuid, this._skeletonData, name);
              if (cache && this._skinName) cache.setSkin(this._skinName);
            }
            if (cache) {
              this._animationName = name;
              this._isAniComplete = false;
              this._accTime = 0;
              this._playCount = 0;
              this._animCache = cache;
              if (this._socketNodes.size > 0) {
                this._animCache.enableCacheAttachedInfo();
              }
              this._animCache.updateToFrame(0);
              this._curFrame = this._animCache.frames[0];
            }
          } else {
            this._animationName = name;
            trackEntry = this._instance.setAnimation(trackIndex, name, loop);
          }
          this.markForUpdateRenderData();
          return trackEntry;
        }
        addAnimation(trackIndex, name, loop, delay) {
          delay = delay || 0;
          if (this.isAnimationCached()) {
            if (trackIndex !== 0) {
              warn('Track index can not greater than 0 in cached mode.');
            }
            this._animationQueue.push({
              animationName: name,
              loop,
              delay
            });
            return null;
          } else if (this._skeleton) {
            var _this$_state;
            const animation = this._skeleton.data.findAnimation(name);
            if (!animation) {
              logID(7510, name);
              return null;
            }
            return (_this$_state = this._state) === null || _this$_state === void 0 ? void 0 : _this$_state.addAnimationWith(trackIndex, animation, loop, delay);
          }
          return null;
        }
        findAnimation(name) {
          if (this._skeleton) {
            return this._skeleton.data.findAnimation(name);
          }
          return null;
        }
        getCurrent(trackIndex) {
          if (this.isAnimationCached()) {
            warn('\'getCurrent\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            return this._state.getCurrent(trackIndex);
          }
          return null;
        }
        setSkin(name) {
          if (!name) return;
          if (this._skeleton) this._skeleton.setSkinByName(name);
          this._instance.setSkin(name);
          if (this.isAnimationCached()) {
            if (this._animCache) {
              this._animCache.setSkin(name);
            }
          }
          this._skinName = name;
          this.invalidAnimationCache();
        }
        updateAnimation(dt) {
          this.markForUpdateRenderData();
          if (this.paused) return;
          if (this.isAnimationCached()) {
            dt *= this._timeScale * timeScale;
            if (this._isAniComplete) {
              var _this$_headAniInfo;
              if (this._animationQueue.length === 0 && !this._headAniInfo) {
                const frameCache = this._animCache;
                if (frameCache && frameCache.isInvalid()) {
                  frameCache.updateToFrame(0);
                  const frames = frameCache.frames;
                  this._curFrame = frames[frames.length - 1];
                }
                return;
              }
              if (!this._headAniInfo) {
                this._headAniInfo = this._animationQueue.shift();
              }
              this._accTime += dt;
              if (this._accTime > ((_this$_headAniInfo = this._headAniInfo) === null || _this$_headAniInfo === void 0 ? void 0 : _this$_headAniInfo.delay)) {
                const aniInfo = this._headAniInfo;
                this._headAniInfo = null;
                this.setAnimation(0, aniInfo === null || aniInfo === void 0 ? void 0 : aniInfo.animationName, aniInfo === null || aniInfo === void 0 ? void 0 : aniInfo.loop);
              }
              return;
            }
            this._updateCache(dt);
          } else {
            this._instance.updateAnimation(dt);
          }
        }
        _updateCache(dt) {
          const frameCache = this._animCache;
          if (!frameCache.isInited()) {
            return;
          }
          const frames = frameCache.frames;
          const frameTime = SkeletonCache.FrameTime;
          if (this._accTime === 0 && this._playCount === 0) {
            this._startEntry.animation.name = this._animationName;
            if (this._listener && this._listener.start) {
              this._listener.start(this._startEntry);
            }
          }
          this._accTime += dt;
          let frameIdx = Math.floor(this._accTime / frameTime);
          if (!frameCache.isCompleted) {
            frameCache.updateToFrame(frameIdx);
          }
          this._curFrame = frames[frameIdx];
          if (this._curFrame !== undefined) {
            this.attachUtil.updateSkeletonBones(this._curFrame.boneInfos);
          }
          if (frameCache.isCompleted && frameIdx >= frames.length) {
            this._playCount++;
            if (this._playTimes > 0 && this._playCount >= this._playTimes) {
              this._curFrame = frames[frames.length - 1];
              this._accTime = 0;
              this._playCount = 0;
              this._isAniComplete = true;
              this._emitCacheCompleteEvent();
              return;
            }
            this._accTime = 0;
            frameIdx = 0;
            this._curFrame = frames[frameIdx];
            this._emitCacheCompleteEvent();
          }
        }
        _emitCacheCompleteEvent() {
          if (!this._listener) return;
          this._endEntry.animation.name = this._animationName;
          if (this._listener.complete) this._listener.complete(this._endEntry);
          if (this._listener.end) this._listener.end(this._endEntry);
        }
        updateRenderData() {
          if (this.isAnimationCached()) {
            if (!this._curFrame) return null;
            const model = this._curFrame.model;
            return model;
          } else {
            const model = this._instance.updateRenderData();
            return model;
          }
        }
        _flushAssembler() {
          const assembler = Skeleton.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._skeleton && this._assembler) {
            this._renderData = this._assembler.createData(this);
            this.markForUpdateRenderData();
            this._updateColor();
          }
        }
        _render(batcher) {
          let indicesCount = 0;
          if (this.renderData && this._drawList.length > 0) {
            const rd = this.renderData;
            const chunk = rd.chunk;
            const accessor = chunk.vertexAccessor;
            const meshBuffer = rd.getMeshBuffer();
            const origin = meshBuffer.indexOffset;
            for (let i = 0; i < this._drawList.length; i++) {
              const dc = this._drawList.data[i];
              if (dc.texture) {
                batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, dc.indexCount, dc.texture, dc.material, this._enableBatch);
              }
              indicesCount += dc.indexCount;
            }
            const subIndices = rd.indices.subarray(0, indicesCount);
            accessor.appendIndices(chunk.bufferId, subIndices);
            accessor.getMeshBuffer(chunk.bufferId).setDirty();
          }
        }
        requestDrawData(material, textureID, indexOffset, indexCount) {
          const draw = this._drawList.add();
          draw.material = material;
          if (textureID < CUSTOM_SLOT_TEXTURE_BEGIN) {
            draw.texture = this._textures[textureID];
          } else {
            var _this$_slotTextures2;
            const texture = (_this$_slotTextures2 = this._slotTextures) === null || _this$_slotTextures2 === void 0 ? void 0 : _this$_slotTextures2.get(textureID);
            if (texture) draw.texture = texture;
          }
          draw.indexOffset = indexOffset;
          draw.indexCount = indexCount;
          return draw;
        }
        _updateBuiltinMaterial() {
          const material = builtinResMgr.get('default-spine-material');
          return material;
        }
        updateMaterial() {
          let mat;
          if (this._customMaterial) mat = this._customMaterial;else mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          this._cleanMaterialCache();
        }
        getMaterialTemplate() {
          if (this.customMaterial !== null) return this.customMaterial;
          if (this.material) return this.material;
          this.updateMaterial();
          return this.material;
        }
        _cleanMaterialCache() {
          for (const val in this._materialCache) {
            this._materialCache[val].destroy();
          }
          this._materialCache = {};
        }
        getMaterialForBlendAndTint(src, dst, type) {
          const key = `${type}/${src}/${dst}`;
          let inst = this._materialCache[key];
          if (inst) {
            return inst;
          }
          const material = this.getMaterialTemplate();
          const matInfo = {
            parent: material,
            subModelIdx: 0,
            owner: this
          };
          inst = new MaterialInstance(matInfo);
          this._materialCache[key] = inst;
          inst.overridePipelineStates({
            blendState: {
              blendColor: Color$1.WHITE,
              targets: [{
                blendEq: 0,
                blendAlphaEq: 0,
                blendSrc: src,
                blendDst: dst,
                blendSrcAlpha: src,
                blendDstAlpha: dst
              }]
            }
          });
          let useTwoColor = false;
          if (type === 1) {
            useTwoColor = true;
          }
          const useLocal = !this._enableBatch;
          inst.recompileShaders({
            TWO_COLORED: useTwoColor,
            USE_LOCAL: useLocal
          });
          return inst;
        }
        _updateAnimEnum() {
          let animEnum;
          if (this.skeletonData) {
            animEnum = this.skeletonData.getAnimsEnum();
          } else {
            animEnum = SpineDefaultAnimsEnum;
          }
          this._enumAnimations = Enum({});
          Object.assign(this._enumAnimations, animEnum);
          Enum.update(this._enumAnimations);
          setPropertyEnumType(this, '_animationIndex', this._enumAnimations);
        }
        _updateSkinEnum() {
          let skinEnum;
          if (this.skeletonData) {
            skinEnum = this.skeletonData.getSkinsEnum();
          } else {
            skinEnum = DefaultSkinsEnum;
          }
          this._enumSkins = Enum({});
          Object.assign(this._enumSkins, skinEnum);
          Enum.update(this._enumSkins);
          setPropertyEnumType(this, '_defaultSkinIndex', this._enumSkins);
        }
        _refreshInspector() {
        }
        destroyRenderData() {
          this._drawList.reset();
          super.destroyRenderData();
        }
        createRenderEntity() {
          const renderEntity = new RenderEntity(1);
          renderEntity.setUseLocal(true);
          return renderEntity;
        }
        markForUpdateRenderData(enable = true) {
          super.markForUpdateRenderData(enable);
          if (this._debugRenderer) {
            this._debugRenderer.markForUpdateRenderData(enable);
          }
        }
        syncAttachedNode() {
          this.attachUtil._syncAttachedNode();
        }
        isAnimationCached() {
          return this._cacheMode !== 0;
        }
        setAnimationCacheMode(cacheMode) {
          if (this._preCacheMode !== cacheMode) {
            this._cacheMode = cacheMode;
            this._preCacheMode = cacheMode;
            if (this._instance) {
              this._instance.isCache = this.isAnimationCached();
            }
            this._updateSkeletonData();
            this.markForUpdateRenderData();
          }
        }
        setToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setToSetupPose();
          }
        }
        setBonesToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setBonesToSetupPose();
          }
        }
        setSlotsToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setSlotsToSetupPose();
          }
        }
        invalidAnimationCache() {
          if (!this.isAnimationCached()) return;
          if (this._skeletonCache) {
            this._skeletonCache.invalidAnimationCache(this._skeletonData.uuid);
          }
        }
        findBone(boneName) {
          if (this._skeleton) {
            return this._skeleton.findBone(boneName);
          }
          return null;
        }
        findSlot(slotName) {
          if (this._skeleton) {
            return this._skeleton.findSlot(slotName);
          }
          return null;
        }
        setMix(fromAnimation, toAnimation, duration) {
          if (this.isAnimationCached()) {
            warn('cached mode not support setMix!!!');
            return;
          }
          if (this._state) {
            this._instance.setMix(fromAnimation, toAnimation, duration);
          }
        }
        clearTracks() {
          if (this.isAnimationCached()) {
            warn('\'clearTracks\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            this._state.clearTracks();
            this.setToSetupPose();
          }
        }
        clearTrack(trackIndex) {
          if (this.isAnimationCached()) {
            warn('\'clearTrack\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            this._state.clearTrack(trackIndex);
          }
        }
        updateWorldTransform() {
          if (!this.isAnimationCached()) return;
          if (this._skeleton) {
            this._skeleton.updateWorldTransform();
          }
        }
        _verifySockets(sockets) {
          for (let i = 0, l = sockets.length; i < l; i++) {
            const target = sockets[i].target;
            if (target) {
              if (!target.parent || target.parent !== this.node) {
                error(`Target node ${target.name} is expected to be a direct child of ${this.node.name}`);
                continue;
              }
            }
          }
          const uniqueSocketNode = new Map();
          sockets.forEach(x => {
            if (x.target) {
              if (uniqueSocketNode.get(x.target)) {
                error(`Target node ${x.target.name} has existed.`);
              } else {
                uniqueSocketNode.set(x.target, true);
              }
            }
          });
        }
        _updateSocketBindings() {
          if (!this._skeleton) return;
          this._socketNodes.clear();
          for (let i = 0, l = this._sockets.length; i < l; i++) {
            const socket = this._sockets[i];
            if (socket.path && socket.target) {
              const boneIdx = this._cachedSockets.get(socket.path);
              if (!boneIdx) {
                error(`Skeleton data does not contain path ${socket.path}`);
                continue;
              }
              this._socketNodes.set(boneIdx, socket.target);
            }
          }
        }
        _indexBoneSockets() {
          if (!this._skeleton) {
            return;
          }
          this._cachedSockets.clear();
          const bones = this._skeleton.bones;
          const getBoneName = bone => {
            if (bone.parent == null) return bone.data.name || '<Unamed>';
            return `${getBoneName(bones[bone.parent.data.index])}/${bone.data.name}`;
          };
          for (let i = 0, l = bones.length; i < l; i++) {
            const bd = bones[i].data;
            const boneName = getBoneName(bones[i]);
            this._cachedSockets.set(boneName, bd.index);
          }
        }
        querySockets() {
          if (!this._skeleton) {
            return [];
          }
          if (this._cachedSockets.size === 0) {
            this._indexBoneSockets();
          }
          if (this._cachedSockets.size > 0) {
            return Array.from(this._cachedSockets.keys()).sort();
          }
          return [];
        }
        _updateUseTint() {
          this._cleanMaterialCache();
          this.destroyRenderData();
          if (this._assembler && this._skeleton) {
            this._renderData = this._assembler.createData(this);
            this.markForUpdateRenderData();
          }
        }
        _updateBatch() {
          this._cleanMaterialCache();
          this.markForUpdateRenderData();
        }
        _updateDebugDraw() {
          if (this.debugBones || this.debugSlots || this.debugMesh) {
            if (!this._debugRenderer) {
              const debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
              debugDrawNode.layer = this.node.layer;
              debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
              const debugDraw = debugDrawNode.addComponent(Graphics);
              debugDraw.lineWidth = 5;
              debugDraw.strokeColor = new Color$1(255, 0, 0, 255);
              this._debugRenderer = debugDraw;
              debugDrawNode.parent = this.node;
              this.node.on("layer-changed", this._applyLayer, this);
            }
            if (this.isAnimationCached()) {
              warn('Debug bones or slots is invalid in cached mode');
            }
          } else if (this._debugRenderer) {
            this.node.off("layer-changed", this._applyLayer, this);
            this._debugRenderer.node.destroy();
            this._debugRenderer = null;
            if (!this.isAnimationCached()) {
              if (this._instance) {
                this._instance.setDebugMode(false);
              }
            }
          }
        }
        _updateUITransform() {
          const uiTrans = this.node._uiProps.uiTransformComp;
          const skeletonData = this._runtimeData;
          if (!skeletonData) {
            uiTrans.setContentSize(100, 100);
            uiTrans.anchorX = 0.5;
            uiTrans.anchorX = 0.5;
            return;
          }
          const width = skeletonData.width;
          const height = skeletonData.height;
          if (width && height) {
            uiTrans.setContentSize(width, height);
            if (width !== 0) uiTrans.anchorX = Math.abs(skeletonData.x) / width;
            if (height !== 0) uiTrans.anchorY = Math.abs(skeletonData.y) / height;
          }
        }
        _updateColor() {
          const a = this.node._uiProps.opacity;
          if (this._tempColor.r === this._color.r && this._tempColor.g === this._color.g && this._tempColor.b === this._color.b && this._tempColor.a === a) {
            return;
          }
          this.node._uiProps.colorDirty = true;
          this._tempColor.r = this._color.r;
          this._tempColor.g = this._color.g;
          this._tempColor.b = this._color.b;
          this._tempColor.a = a;
          const r = this._color.r / 255.0;
          const g = this._color.g / 255.0;
          const b = this._color.b / 255.0;
          this._instance.setColor(r, g, b, a);
        }
        setVertexEffectDelegate(effectDelegate) {
          if (!this._instance) {
            return;
          }
          if (!effectDelegate) {
            this._instance.clearEffect();
            return;
          }
          const effectType = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getEffectType();
          if (effectType === 'jitter') {
            const jitterEffect = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getJitterVertexEffect();
            this._instance.setJitterEffect(jitterEffect);
          } else if (effectType === 'swirl') {
            const swirlEffect = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getJitterVertexEffect();
            this._instance.setSwirlEffect(swirlEffect);
          }
        }
        _ensureListener() {
          if (!this._listener) {
            this._listener = new TrackEntryListeners();
            this._eventListenerID = TrackEntryListeners.addListener(this._listener);
            this._instance.setListener(this._eventListenerID);
          }
        }
        setStartListener(listener) {
          this._ensureListener();
          this._listener.start = listener;
        }
        setInterruptListener(listener) {
          this._ensureListener();
          this._listener.interrupt = listener;
        }
        setEndListener(listener) {
          this._ensureListener();
          this._listener.end = listener;
        }
        setDisposeListener(listener) {
          this._ensureListener();
          this._listener.dispose = listener;
        }
        setCompleteListener(listener) {
          this._ensureListener();
          this._listener.complete = listener;
        }
        setEventListener(listener) {
          this._ensureListener();
          this._listener.event = listener;
        }
        setTrackStartListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).start = listener;
        }
        setTrackInterruptListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).interrupt = listener;
        }
        setTrackEndListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).end = listener;
        }
        setTrackDisposeListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).dispose = listener;
        }
        setTrackCompleteListener(entry, listener) {
          const onComplete = trackEntry => {
            const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
            listener(trackEntry, loopCount);
          };
          TrackEntryListeners.getListeners(entry, this._instance).complete = onComplete;
        }
        setTrackEventListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).event = listener;
        }
        getDebugShapes() {
          return this._instance.getDebugShapes();
        }
        setSlotTexture(slotName, tex2d, createNew) {
          if (this.isAnimationCached()) {
            error(`Cached mode can't change texture of slot`);
            return;
          }
          const slot = this.findSlot(slotName);
          if (!slot) {
            error(`No slot named:${slotName}`);
            return;
          }
          const width = tex2d.width;
          const height = tex2d.height;
          const createNewAttachment = createNew || false;
          this._instance.resizeSlotRegion(slotName, width, height, createNewAttachment);
          if (!this._slotTextures) this._slotTextures = new Map();
          let textureID = 0;
          this._slotTextures.forEach((value, key) => {
            if (value === tex2d) textureID = key;
          });
          if (textureID === 0) {
            textureID = ++_slotTextureID;
            this._slotTextures.set(textureID, tex2d);
          }
          this._instance.setSlotTexture(slotName, textureID);
        }
        _destroySkeletonInfo(skeletonCache) {
          if (skeletonCache && this._skeletonInfo) {
            skeletonCache.destroySkeleton(this._skeletonInfo.assetUUID);
            this._skeletonInfo = null;
          }
        }
        _applyLayer() {
          if (this._debugRenderer) {
            this._debugRenderer.node.layer = this.node.layer;
          }
        }
      }, _class6.SpineSocket = SpineSocket, _class6.AnimationCacheMode = SpineAnimationCacheMode, _class6), (_initializer3$f = applyDecoratedInitializer(_class5.prototype, "_skeletonData", [serializable$l], function () {
        return null;
      }), _initializer4$d = applyDecoratedInitializer(_class5.prototype, "defaultSkin", [serializable$l], function () {
        return '';
      }), _initializer5$b = applyDecoratedInitializer(_class5.prototype, "defaultAnimation", [serializable$l], function () {
        return '';
      }), _initializer6$8 = applyDecoratedInitializer(_class5.prototype, "_premultipliedAlpha", [serializable$l], function () {
        return true;
      }), _initializer7$8 = applyDecoratedInitializer(_class5.prototype, "_timeScale", [serializable$l], function () {
        return 1;
      }), _initializer8$8 = applyDecoratedInitializer(_class5.prototype, "_preCacheMode", [serializable$l], function () {
        return -1;
      }), _initializer9$7 = applyDecoratedInitializer(_class5.prototype, "_cacheMode", [serializable$l], function () {
        return 0;
      }), _initializer10$7 = applyDecoratedInitializer(_class5.prototype, "_sockets", [serializable$l], function () {
        return [];
      }), _initializer11$7 = applyDecoratedInitializer(_class5.prototype, "_useTint", [serializable$l], function () {
        return false;
      }), _initializer12$6 = applyDecoratedInitializer(_class5.prototype, "_debugMesh", [serializable$l], function () {
        return false;
      }), _initializer13$4 = applyDecoratedInitializer(_class5.prototype, "_debugBones", [serializable$l], function () {
        return false;
      }), _initializer14$3 = applyDecoratedInitializer(_class5.prototype, "_debugSlots", [serializable$l], function () {
        return false;
      }), _initializer15$2 = applyDecoratedInitializer(_class5.prototype, "_enableBatch", [serializable$l], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5.prototype, "skeletonData", [_dec4$f], Object.getOwnPropertyDescriptor(_class5.prototype, "skeletonData"), _class5.prototype), _applyDecoratedDescriptor(_class5.prototype, "_defaultSkinIndex", [_dec5$f], Object.getOwnPropertyDescriptor(_class5.prototype, "_defaultSkinIndex"), _class5.prototype), _applyDecoratedDescriptor(_class5.prototype, "_animationIndex", [_dec6$9], Object.getOwnPropertyDescriptor(_class5.prototype, "_animationIndex"), _class5.prototype), _applyDecoratedDescriptor(_class5.prototype, "defaultCacheMode", [_dec7$7], Object.getOwnPropertyDescriptor(_class5.prototype, "defaultCacheMode"), _class5.prototype), _initializer16$2 = applyDecoratedInitializer(_class5.prototype, "loop", [serializable$l], function () {
        return true;
      }), _applyDecoratedDescriptor(_class5.prototype, "sockets", [_dec8$5], Object.getOwnPropertyDescriptor(_class5.prototype, "sockets"), _class5.prototype), _applyDecoratedDescriptor(_class5.prototype, "customMaterial", [override$1, _dec9$4], Object.getOwnPropertyDescriptor(_class5.prototype, "customMaterial"), _class5.prototype)), _class5)) || _class4);
      legacyCC.internal.SpineSkeleton = Skeleton;

      const _slotColor = new Color$1(0, 0, 255, 255);
      const _boneColor = new Color$1(255, 0, 0, 255);
      const _originColor = new Color$1(0, 255, 0, 255);
      const _meshColor = new Color$1(255, 255, 0, 255);
      let _nodeR;
      let _nodeG;
      let _nodeB;
      let _nodeA;
      let _accessor$1 = null;
      let _tintAccessor = null;
      let _premultipliedAlpha = false;
      let _useTint = false;
      const _byteStrideOneColor = getAttributeStride(vfmtPosUvColor4B);
      const _byteStrideTwoColor = getAttributeStride(vfmtPosUvTwoColor4B);
      const DEBUG_TYPE_REGION = 0;
      const DEBUG_TYPE_MESH = 1;
      const tempVecPos = new Vec3(0, 0, 0);
      function _getSlotMaterial(blendMode, comp) {
        let src;
        let dst;
        switch (blendMode) {
          case 1:
            src = _premultipliedAlpha ? 1 : 2;
            dst = 1;
            break;
          case 2:
            src = 7;
            dst = 4;
            break;
          case 3:
            src = _premultipliedAlpha ? 1 : 2;
            dst = 8;
            break;
          case 0:
          default:
            src = _premultipliedAlpha ? 1 : 2;
            dst = 4;
            break;
        }
        return comp.getMaterialForBlendAndTint(src, dst, _useTint ? 1 : 0);
      }
      const simple$1 = {
        vCount: 32767,
        ensureAccessor(useTint) {
          let accessor = useTint ? _tintAccessor : _accessor$1;
          if (!accessor) {
            const device = director.root.device;
            const batcher = director.root.batcher2D;
            const attributes = useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B;
            if (useTint) {
              accessor = _tintAccessor = new StaticVBAccessor(device, attributes, this.vCount);
              batcher.registerBufferAccessor(Number.parseInt('SPINETINT', 36), _tintAccessor);
            } else {
              accessor = _accessor$1 = new StaticVBAccessor(device, attributes, this.vCount);
              batcher.registerBufferAccessor(Number.parseInt('SPINE', 36), _accessor$1);
            }
          }
          return accessor;
        },
        createData(comp) {
          let rd = comp.renderData;
          if (!rd) {
            const useTint = comp.useTint || comp.isAnimationCached();
            const accessor = this.ensureAccessor(useTint);
            rd = RenderData.add(useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B, accessor);
          }
          return rd;
        },
        updateRenderData(comp, batcher) {
          var _comp$skeletonData;
          const skeleton = comp._skeleton;
          if (skeleton && comp.node.active && (_comp$skeletonData = comp.skeletonData) !== null && _comp$skeletonData !== void 0 && _comp$skeletonData.isValid) {
            updateComponentRenderData(comp);
          }
        }
      };
      function updateComponentRenderData(comp, batcher) {
        comp.drawList.reset();
        if (comp.color.a === 0) return;
        comp._updateColor();
        _premultipliedAlpha = comp.premultipliedAlpha;
        _useTint = comp.useTint || comp.isAnimationCached();
        if (comp.isAnimationCached()) {
          cacheTraverse(comp);
        } else {
          realTimeTraverse(comp);
        }
        const rd = comp.renderData;
        const accessor = _useTint ? _tintAccessor : _accessor$1;
        comp.syncAttachedNode();
        if (rd.vertexCount > 0 || rd.indexCount > 0) accessor.getMeshBuffer(rd.chunk.bufferId).setDirty();
      }
      function realTimeTraverse(comp) {
        var _comp$_vBuffer, _comp$_iBuffer;
        const floatStride = (comp.useTint ? _byteStrideTwoColor : _byteStrideOneColor) / 4;
        const model = comp.updateRenderData();
        const vc = model.vCount;
        const ic = model.iCount;
        if (vc < 1 || ic < 1) return;
        const rd = comp.renderData;
        if (rd.vertexCount !== vc || rd.indexCount !== ic) {
          rd.resize(vc, ic);
          rd.indices = new Uint16Array(ic);
          comp._vLength = vc * 4 * floatStride;
          comp._vBuffer = new Uint8Array(rd.chunk.vb.buffer, rd.chunk.vb.byteOffset, 4 * rd.chunk.vb.length);
          comp._iLength = 2 * ic;
          comp._iBuffer = new Uint8Array(rd.indices.buffer);
        }
        const vbuf = rd.chunk.vb;
        const vPtr = model.vPtr;
        const iPtr = model.iPtr;
        const ibuf = rd.indices;
        const HEAPU8 = spineLib.wasmUtil.wasm.HEAPU8;
        (_comp$_vBuffer = comp._vBuffer) === null || _comp$_vBuffer === void 0 ? void 0 : _comp$_vBuffer.set(HEAPU8.subarray(vPtr, vPtr + comp._vLength), 0);
        (_comp$_iBuffer = comp._iBuffer) === null || _comp$_iBuffer === void 0 ? void 0 : _comp$_iBuffer.set(HEAPU8.subarray(iPtr, iPtr + comp._iLength), 0);
        const chunkOffset = rd.chunk.vertexOffset;
        for (let i = 0; i < ic; i++) ibuf[i] += chunkOffset;
        const data = model.getData();
        const count = data.size();
        let indexOffset = 0;
        let indexCount = 0;
        for (let i = 0; i < count; i += 6) {
          indexCount = data.get(i + 3);
          const material = _getSlotMaterial(data.get(i + 4), comp);
          const textureID = data.get(i + 5);
          comp.requestDrawData(material, textureID, indexOffset, indexCount);
          indexOffset += indexCount;
        }
        if (comp.enableBatch) {
          const worldMat = comp.node.worldMatrix;
          let index = 0;
          for (let i = 0; i < vc; i++) {
            index = i * floatStride;
            tempVecPos.x = vbuf[index];
            tempVecPos.y = vbuf[index + 1];
            tempVecPos.z = 0;
            tempVecPos.transformMat4(worldMat);
            vbuf[index] = tempVecPos.x;
            vbuf[index + 1] = tempVecPos.y;
            vbuf[index + 2] = tempVecPos.z;
          }
        }
        const graphics = comp._debugRenderer;
        const locSkeleton = comp._skeleton;
        if (graphics && (comp.debugBones || comp.debugSlots || comp.debugMesh)) {
          graphics.clear();
          const debugShapes = comp.getDebugShapes();
          const shapeCount = debugShapes.size();
          for (let i = 0; i < shapeCount; i++) {
            const shape = debugShapes.get(i);
            if (shape.type === DEBUG_TYPE_REGION && comp.debugSlots) {
              graphics.strokeColor = _slotColor;
              const vertexFloatOffset = shape.vOffset * floatStride;
              const vertexFloatCount = shape.vCount * floatStride;
              graphics.moveTo(vbuf[vertexFloatOffset], vbuf[vertexFloatOffset + 1]);
              for (let ii = vertexFloatOffset + floatStride, nn = vertexFloatOffset + vertexFloatCount; ii < nn; ii += floatStride) {
                graphics.lineTo(vbuf[ii], vbuf[ii + 1]);
              }
              graphics.close();
              graphics.stroke();
            } else if (shape.type === DEBUG_TYPE_MESH && comp.debugMesh) {
              graphics.strokeColor = _meshColor;
              const iCount = shape.iCount;
              const iOffset = shape.iOffset;
              for (let ii = iOffset, nn = iOffset + iCount; ii < nn; ii += 3) {
                const v1 = ibuf[ii] * floatStride;
                const v2 = ibuf[ii + 1] * floatStride;
                const v3 = ibuf[ii + 2] * floatStride;
                graphics.moveTo(vbuf[v1], vbuf[v1 + 1]);
                graphics.lineTo(vbuf[v2], vbuf[v2 + 1]);
                graphics.lineTo(vbuf[v3], vbuf[v3 + 1]);
                graphics.close();
                graphics.stroke();
              }
            }
          }
          if (comp.debugBones) {
            graphics.strokeColor = _boneColor;
            graphics.fillColor = _slotColor;
            for (let i = 0, n = locSkeleton.bones.length; i < n; i++) {
              const bone = locSkeleton.bones[i];
              const x = bone.data.length * bone.a + bone.worldX;
              const y = bone.data.length * bone.c + bone.worldY;
              graphics.moveTo(bone.worldX, bone.worldY);
              graphics.lineTo(x, y);
              graphics.stroke();
              graphics.circle(bone.worldX, bone.worldY, Math.PI * 1.5);
              graphics.fill();
              if (i === 0) {
                graphics.fillColor = _originColor;
              }
            }
          }
        }
      }
      function cacheTraverse(comp) {
        const model = comp.updateRenderData();
        if (!model) return;
        const vc = model.vCount;
        const ic = model.iCount;
        if (vc < 1 || ic < 1) return;
        const rd = comp.renderData;
        if (rd.vertexCount !== vc || rd.indexCount !== ic) {
          rd.resize(vc, ic);
          rd.indices = new Uint16Array(ic);
        }
        const vbuf = rd.chunk.vb;
        const vUint8Buf = new Uint8Array(vbuf.buffer, vbuf.byteOffset, 4 * vbuf.length);
        vUint8Buf.set(model.vData);
        const nodeColor = comp.color;
        const opacity = comp.node._uiProps.opacity;
        if (1 - opacity > EPSILON$2 || Color$1.toUint32(nodeColor) !== 0xffffffff || _premultipliedAlpha) {
          _nodeR = nodeColor.r / 255;
          _nodeG = nodeColor.g / 255;
          _nodeB = nodeColor.b / 255;
          _nodeA = opacity;
          for (let i = 0; i < vc; i++) {
            const index = i * _byteStrideTwoColor + 5 * 4;
            const R = vUint8Buf[index];
            const G = vUint8Buf[index + 1];
            const B = vUint8Buf[index + 2];
            const A = vUint8Buf[index + 3];
            const fA = A * _nodeA;
            const multiplier = _premultipliedAlpha ? fA / 255 : 1;
            vUint8Buf[index] = Math.floor(multiplier * R * _nodeR);
            vUint8Buf[index + 1] = Math.floor(multiplier * G * _nodeG);
            vUint8Buf[index + 2] = Math.floor(multiplier * B * _nodeB);
            vUint8Buf[index + 3] = Math.floor(fA);
            vUint8Buf[index + 4] = Math.floor(vUint8Buf[index + 4] * _nodeR);
            vUint8Buf[index + 5] = Math.floor(vUint8Buf[index + 5] * _nodeG);
            vUint8Buf[index + 6] = Math.floor(vUint8Buf[index + 6] * _nodeB);
            vUint8Buf[index + 7] = _premultipliedAlpha ? 255 : 0;
          }
        }
        const iUint16Buf = rd.indices;
        iUint16Buf.set(model.iData);
        const chunkOffset = rd.chunk.vertexOffset;
        for (let i = 0; i < ic; i++) {
          iUint16Buf[i] += chunkOffset;
        }
        const meshes = model.meshes;
        const count = meshes.length;
        let indexOffset = 0;
        let indexCount = 0;
        for (let i = 0; i < count; i++) {
          const mesh = meshes[i];
          const material = _getSlotMaterial(mesh.blendMode, comp);
          const textureID = mesh.textureID;
          indexCount = mesh.iCount;
          comp.requestDrawData(material, textureID, indexOffset, indexCount);
          indexOffset += indexCount;
        }
        const floatStride = _byteStrideTwoColor / 4;
        if (comp.enableBatch) {
          const worldMat = comp.node.worldMatrix;
          let index = 0;
          for (let i = 0; i < vc; i++) {
            index = i * floatStride;
            tempVecPos.x = vbuf[index];
            tempVecPos.y = vbuf[index + 1];
            tempVecPos.z = 0;
            tempVecPos.transformMat4(worldMat);
            vbuf[index] = tempVecPos.x;
            vbuf[index + 1] = tempVecPos.y;
            vbuf[index + 2] = tempVecPos.z;
          }
        }
      }
      legacyCC.internal.SpineAssembler = simple$1;

      const simpleSpineAssembler = {
        getAssembler() {
          return simple$1;
        }
      };
      Skeleton.Assembler = simpleSpineAssembler;

      const spine = globalThis.spine;
      spine.EventType = spineLib.EventType;
      const VertexEffectDelegate = spine.VertexEffectDelegate;
      let ATTACHMENT_TYPE;
      (function (ATTACHMENT_TYPE) {
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["REGION"] = 0] = "REGION";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["BOUNDING_BOX"] = 1] = "BOUNDING_BOX";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["MESH"] = 2] = "MESH";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["SKINNED_MESH"] = 3] = "SKINNED_MESH";
      })(ATTACHMENT_TYPE || (ATTACHMENT_TYPE = {}));
      ccenum(ATTACHMENT_TYPE);
      let AnimationEventType;
      (function (AnimationEventType) {
        AnimationEventType[AnimationEventType["START"] = 0] = "START";
        AnimationEventType[AnimationEventType["INTERRUPT"] = 1] = "INTERRUPT";
        AnimationEventType[AnimationEventType["END"] = 2] = "END";
        AnimationEventType[AnimationEventType["DISPOSE"] = 3] = "DISPOSE";
        AnimationEventType[AnimationEventType["COMPLETE"] = 4] = "COMPLETE";
        AnimationEventType[AnimationEventType["EVENT"] = 5] = "EVENT";
      })(AnimationEventType || (AnimationEventType = {}));
      ccenum(AnimationEventType);
      legacyCC.internal.SpineAnimationEventType = AnimationEventType;
      function loadWasmModuleSpine() {
        return Promise.resolve();
      }

      var index = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get ATTACHMENT_TYPE () { return ATTACHMENT_TYPE; },
        AnimationCacheMode: AnimationCacheMode,
        get AnimationEventType () { return AnimationEventType; },
        DefaultAnimsEnum: DefaultAnimsEnum,
        DefaultSkinsEnum: DefaultSkinsEnum,
        Skeleton: Skeleton,
        SkeletonData: SkeletonData,
        SpineAnimationCacheMode: SpineAnimationCacheMode,
        SpineDefaultAnimsEnum: SpineDefaultAnimsEnum,
        SpineMaterialType: SpineMaterialType,
        SpineSocket: SpineSocket,
        VertexEffectDelegate: VertexEffectDelegate,
        loadWasmModuleSpine: loadWasmModuleSpine,
        simpleSpineAssembler: simpleSpineAssembler,
        spine: spine,
        timeScale: timeScale
      });
      exports("sp", index);

      const Orientation = {
        "ORTHO": 0,
        "HEX": 1,
        "ISO": 2
      };
      ccenum(Orientation);
      const Property = {
        "NONE": 0,
        "MAP": 1,
        "LAYER": 2,
        "OBJECTGROUP": 3,
        "OBJECT": 4,
        "TILE": 5
      };
      ccenum(Property);
      const TileFlag = {
        "HORIZONTAL": 2147483648,
        "VERTICAL": 1073741824,
        "DIAGONAL": 536870912,
        "FLIPPED_ALL": 4026531840,
        "FLIPPED_MASK": 268435455
      };
      ccenum(TileFlag);
      const StaggerAxis = {
        "STAGGERAXIS_X": 0,
        "STAGGERAXIS_Y": 1
      };
      ccenum(StaggerAxis);
      const StaggerIndex = {
        "STAGGERINDEX_ODD": 0,
        "STAGGERINDEX_EVEN": 1
      };
      ccenum(StaggerIndex);
      const RenderOrder = {
        "RightDown": 0,
        "RightUp": 1,
        "LeftDown": 2,
        "LeftUp": 3
      };
      ccenum(RenderOrder);
      const TMXObjectType = {
        "RECT": 0,
        "ELLIPSE": 1,
        "POLYGON": 2,
        "POLYLINE": 3,
        "IMAGE": 4,
        "TEXT": 5
      };
      ccenum(TMXObjectType);
      class TMXTilesetInfo {
        constructor() {
          this.name = '';
          this.firstGid = 0;
          this.spacing = 0;
          this.margin = 0;
          this.sourceImage = void 0;
          this.imageName = null;
          this.imageOffset = null;
          this.imageSize = new Size$1(0, 0);
          this.tileOffset = new Vec2(0, 0);
          this._tileSize = new Size$1(0, 0);
          this.collection = false;
        }
        rectForGID(gid_, result) {
          const rect = result || new Rect$1(0, 0, 0, 0);
          rect.width = this._tileSize.width;
          rect.height = this._tileSize.height;
          let gid = gid_;
          gid &= 268435455;
          gid -= this.firstGid;
          if (this.imageOffset) {
            rect.x = this.imageOffset.x;
            rect.y = this.imageOffset.y;
          } else {
            const max_x = Math.floor((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing));
            rect.x = Math.round(gid % max_x * (this._tileSize.width + this.spacing) + this.margin);
            rect.y = Math.round(Math.floor(gid / max_x) * (this._tileSize.height + this.spacing) + this.margin);
          }
          return rect;
        }
      }
      class TMXObjectGroupInfo {
        constructor() {
          this.properties = {};
          this.name = '';
          this.objects = [];
          this.visible = true;
          this.opacity = 0;
          this.color = new Color$1(255, 255, 255, 255);
          this.offset = new Vec2(0, 0);
          this.draworder = 'topdown';
          this.tintColor = null;
        }
        getProperties() {
          return this.properties;
        }
        setProperties(value) {
          this.properties = value;
        }
      }
      class TMXLayerInfo {
        constructor() {
          this.properties = {};
          this.name = '';
          this.layerSize = null;
          this.tiles = [];
          this.visible = true;
          this.opacity = 0;
          this.ownTiles = true;
          this.minGID = 100000;
          this.maxGID = 0;
          this.offset = new Vec2(0, 0);
          this.tintColor = null;
        }
        getProperties() {
          return this.properties;
        }
        setProperties(value) {
          this.properties = value;
        }
      }
      TMXLayerInfo.ATTRIB_NONE = 1 << 0;
      TMXLayerInfo.ATTRIB_BASE64 = 1 << 1;
      TMXLayerInfo.ATTRIB_GZIP = 1 << 2;
      TMXLayerInfo.ATTRIB_ZLIB = 1 << 3;
      class TMXImageLayerInfo {
        constructor() {
          this.name = '';
          this.visible = true;
          this.width = 0;
          this.height = 0;
          this.offset = new Vec2(0, 0);
          this.opacity = 0;
          this.trans = new Color$1(255, 255, 255, 255);
          this.sourceImage = void 0;
          this.tintColor = null;
        }
      }

      function uint8ArrayToUint32Array(uint8Arr) {
        if (uint8Arr.length % 4 !== 0) return null;
        const arrLen = uint8Arr.length / 4;
        const retArr = window.Uint32Array ? new Uint32Array(arrLen) : [];
        for (let i = 0; i < arrLen; i++) {
          const offset = i * 4;
          retArr[i] = uint8Arr[offset] + uint8Arr[offset + 1] * (1 << 8) + uint8Arr[offset + 2] * (1 << 16) + uint8Arr[offset + 3] * (1 << 24);
        }
        return retArr;
      }
      function strToHAlign(value) {
        const hAlign = Label.HorizontalAlign;
        switch (value) {
          case 'center':
            return hAlign.CENTER;
          case 'right':
            return hAlign.RIGHT;
          default:
            return hAlign.LEFT;
        }
      }
      function strToVAlign(value) {
        const vAlign = Label.VerticalAlign;
        switch (value) {
          case 'center':
            return vAlign.CENTER;
          case 'bottom':
            return vAlign.BOTTOM;
          default:
            return vAlign.TOP;
        }
      }
      function strToColor(value) {
        if (!value) {
          return new Color$1(0, 0, 0, 255);
        }
        value = value.indexOf('#') !== -1 ? value.substring(1) : value;
        if (value.length === 8) {
          const a = parseInt(value.substr(0, 2), 16) || 255;
          const r = parseInt(value.substr(2, 2), 16) || 0;
          const g = parseInt(value.substr(4, 2), 16) || 0;
          const b = parseInt(value.substr(6, 2), 16) || 0;
          return new Color$1(r, g, b, a);
        } else {
          const r = parseInt(value.substr(0, 2), 16) || 0;
          const g = parseInt(value.substr(2, 2), 16) || 0;
          const b = parseInt(value.substr(4, 2), 16) || 0;
          return new Color$1(r, g, b, 255);
        }
      }
      function getPropertyList(node, map) {
        const res = [];
        const properties = Array.from(node.getElementsByTagName('properties')).filter(element => element.parentNode === node);
        for (let i = 0; i < properties.length; ++i) {
          const property = properties[i].getElementsByTagName('property');
          for (let j = 0; j < property.length; ++j) {
            res.push(property[j]);
          }
        }
        map = map || {};
        for (let i = 0; i < res.length; i++) {
          const element = res[i];
          const name = element.getAttribute('name');
          const type = element.getAttribute('type') || 'string';
          let value = element.getAttribute('value');
          if (type === 'int') {
            value = parseInt(value);
          } else if (type === 'float') {
            value = parseFloat(value);
          } else if (type === 'bool') {
            value = value === 'true';
          } else if (type === 'color') {
            value = strToColor(value);
          }
          map[name] = value;
        }
        return map;
      }
      class TMXMapInfo {
        get mapSize() {
          return this._mapSize;
        }
        get tileSize() {
          return this._tileSize;
        }
        constructor(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures) {
          this.properties = {};
          this.orientation = null;
          this.parentElement = null;
          this.parentGID = 0;
          this.layerAttrs = 0;
          this.storingCharacters = false;
          this.currentString = null;
          this.renderOrder = 0;
          this._supportVersion = [1, 4, 0];
          this._objectGroups = [];
          this._allChildren = [];
          this._mapSize = new Size$1(0, 0);
          this._tileSize = new Size$1(0, 0);
          this._layers = [];
          this._tilesets = [];
          this._imageLayers = [];
          this._tileProperties = new Map();
          this._tileAnimations = {};
          this._tsxContentMap = null;
          this._spriteFrameMap = null;
          this._spfSizeMap = {};
          this._staggerAxis = null;
          this._staggerIndex = null;
          this._hexSideLength = 0;
          this._imageLayerSPF = null;
          this.initWithXML(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures);
        }
        getOrientation() {
          return this.orientation;
        }
        setOrientation(value) {
          this.orientation = value;
        }
        getStaggerAxis() {
          return this._staggerAxis;
        }
        setStaggerAxis(value) {
          this._staggerAxis = value;
        }
        getStaggerIndex() {
          return this._staggerIndex;
        }
        setStaggerIndex(value) {
          this._staggerIndex = value;
        }
        getHexSideLength() {
          return this._hexSideLength;
        }
        setHexSideLength(value) {
          this._hexSideLength = value;
        }
        getMapSize() {
          return new Size$1(this._mapSize.width, this._mapSize.height);
        }
        setMapSize(value) {
          this._mapSize.width = value.width;
          this._mapSize.height = value.height;
        }
        get mapWidth() {
          return this._mapSize.width;
        }
        set mapWidth(width) {
          this._mapSize.width = width;
        }
        get mapHeight() {
          return this._mapSize.height;
        }
        set mapHeight(height) {
          this._mapSize.height = height;
        }
        getTileSize() {
          return new Size$1(this._tileSize.width, this._tileSize.height);
        }
        setTileSize(value) {
          this._tileSize.width = value.width;
          this._tileSize.height = value.height;
        }
        get tileWidth() {
          return this._tileSize.width;
        }
        set tileWidth(width) {
          this._tileSize.width = width;
        }
        get tileHeight() {
          return this._tileSize.height;
        }
        set tileHeight(height) {
          this._tileSize.height = height;
        }
        getLayers() {
          return this._layers;
        }
        setLayers(value) {
          this._allChildren.push(value);
          this._layers.push(value);
        }
        getImageLayers() {
          return this._imageLayers;
        }
        setImageLayers(value) {
          this._allChildren.push(value);
          this._imageLayers.push(value);
        }
        getTilesets() {
          return this._tilesets;
        }
        setTilesets(value) {
          this._tilesets.push(value);
        }
        getObjectGroups() {
          return this._objectGroups;
        }
        setObjectGroups(value) {
          this._allChildren.push(value);
          this._objectGroups.push(value);
        }
        getAllChildren() {
          return this._allChildren;
        }
        getParentElement() {
          return this.parentElement;
        }
        setParentElement(value) {
          this.parentElement = value;
        }
        getParentGID() {
          return this.parentGID;
        }
        setParentGID(value) {
          this.parentGID = value;
        }
        getLayerAttribs() {
          return this.layerAttrs;
        }
        setLayerAttribs(value) {
          this.layerAttrs = value;
        }
        getStoringCharacters() {
          return this.storingCharacters;
        }
        setStoringCharacters(value) {
          this.storingCharacters = value;
        }
        getProperties() {
          return this.properties;
        }
        setProperties(value) {
          this.properties = value;
        }
        initWithXML(tmxString, tsxMap, spfTextureMap, textureSizes, imageLayerTextures) {
          this._tilesets.length = 0;
          this._layers.length = 0;
          this._imageLayers.length = 0;
          this._tsxContentMap = tsxMap;
          this._spriteFrameMap = spfTextureMap;
          this._imageLayerSPF = imageLayerTextures;
          this._spfSizeMap = textureSizes;
          this._objectGroups.length = 0;
          this._allChildren.length = 0;
          this.properties = {};
          this._tileProperties = new Map();
          this._tileAnimations = new Map();
          this.currentString = '';
          this.storingCharacters = false;
          this.layerAttrs = TMXLayerInfo.ATTRIB_NONE;
          this.parentElement = null;
          return this.parseXMLString(tmxString);
        }
        parseXMLString(xmlStr, tilesetFirstGid) {
          const parser = new SAXParser();
          const mapXML = parser.parse(xmlStr);
          let i;
          const map = mapXML.documentElement;
          const orientationStr = map.getAttribute('orientation');
          const staggerAxisStr = map.getAttribute('staggeraxis');
          const staggerIndexStr = map.getAttribute('staggerindex');
          const hexSideLengthStr = map.getAttribute('hexsidelength');
          const renderorderStr = map.getAttribute('renderorder');
          const version = map.getAttribute('version') || '1.0.0';
          if (map.nodeName === 'map') {
            const versionArr = version.split('.');
            const supportVersion = this._supportVersion;
            for (i = 0; i < supportVersion.length; i++) {
              const v = parseInt(versionArr[i]) || 0;
              const sv = supportVersion[i];
              if (sv < v) {
                logID(7216, version);
                break;
              }
            }
            if (orientationStr === 'orthogonal') this.orientation = 0;else if (orientationStr === 'isometric') this.orientation = 2;else if (orientationStr === 'hexagonal') this.orientation = 1;else if (orientationStr !== null) logID(7217, orientationStr);
            if (renderorderStr === 'right-up') {
              this.renderOrder = 1;
            } else if (renderorderStr === 'left-up') {
              this.renderOrder = 3;
            } else if (renderorderStr === 'left-down') {
              this.renderOrder = 2;
            } else {
              this.renderOrder = 0;
            }
            if (staggerAxisStr === 'x') {
              this.setStaggerAxis(0);
            } else if (staggerAxisStr === 'y') {
              this.setStaggerAxis(1);
            }
            if (staggerIndexStr === 'odd') {
              this.setStaggerIndex(0);
            } else if (staggerIndexStr === 'even') {
              this.setStaggerIndex(1);
            }
            if (hexSideLengthStr) {
              this.setHexSideLength(parseFloat(hexSideLengthStr));
            }
            let mapSize = new Size$1(0, 0);
            mapSize.width = parseFloat(map.getAttribute('width'));
            mapSize.height = parseFloat(map.getAttribute('height'));
            this.setMapSize(mapSize);
            mapSize = new Size$1(0, 0);
            mapSize.width = parseFloat(map.getAttribute('tilewidth'));
            mapSize.height = parseFloat(map.getAttribute('tileheight'));
            this.setTileSize(mapSize);
            this.properties = getPropertyList(map);
          }
          let tilesets = map.getElementsByTagName('tileset');
          if (map.nodeName !== 'map') {
            tilesets = [];
            tilesets.push(map);
          }
          for (i = 0; i < tilesets.length; i++) {
            const curTileset = tilesets[i];
            const tsxName = curTileset.getAttribute('source');
            if (tsxName) {
              const currentFirstGID = parseInt(curTileset.getAttribute('firstgid'));
              const tsxXmlString = this._tsxContentMap[tsxName];
              if (tsxXmlString) {
                this.parseXMLString(tsxXmlString, currentFirstGID);
              }
            } else {
              const images = curTileset.getElementsByTagName('image');
              const collection = images.length > 1;
              const firstImage = images[0];
              let firstImageName = firstImage.getAttribute('source');
              firstImageName = firstImageName.replace(/\\/g, '/');
              const tiles = curTileset.getElementsByTagName('tile');
              const tileCount = tiles && tiles.length || 1;
              let tile = null;
              const tilesetName = curTileset.getAttribute('name') || '';
              const tilesetSpacing = parseInt(curTileset.getAttribute('spacing')) || 0;
              const tilesetMargin = parseInt(curTileset.getAttribute('margin')) || 0;
              const fgid = tilesetFirstGid || parseInt(curTileset.getAttribute('firstgid')) || 0;
              const tilesetSize = new Size$1(0, 0);
              tilesetSize.width = parseFloat(curTileset.getAttribute('tilewidth'));
              tilesetSize.height = parseFloat(curTileset.getAttribute('tileheight'));
              const curTileOffset = curTileset.getElementsByTagName('tileoffset')[0];
              let tileOffsetX = 0;
              let tileOffsetY = 0;
              if (curTileOffset) {
                tileOffsetX = parseFloat(curTileOffset.getAttribute('x')) || 0;
                tileOffsetY = parseFloat(curTileOffset.getAttribute('y')) || 0;
              }
              let tileset = null;
              for (let tileIdx = 0; tileIdx < tileCount; tileIdx++) {
                const curImage = images[tileIdx] ? images[tileIdx] : firstImage;
                if (!curImage) continue;
                let curImageName = curImage.getAttribute('source');
                curImageName = curImageName.replace(/\\/g, '/');
                if (!tileset || collection) {
                  tileset = new TMXTilesetInfo();
                  tileset.name = tilesetName;
                  tileset.firstGid = fgid & 268435455;
                  tileset.tileOffset.x = tileOffsetX;
                  tileset.tileOffset.y = tileOffsetY;
                  tileset.collection = collection;
                  if (!collection) {
                    tileset.imageName = curImageName;
                    tileset.imageSize.width = parseFloat(curImage.getAttribute('width')) || 0;
                    tileset.imageSize.height = parseFloat(curImage.getAttribute('height')) || 0;
                    tileset.sourceImage = this._spriteFrameMap[curImageName];
                    if (!tileset.sourceImage) {
                      const nameWithPostfix = TMXMapInfo.getNameWithPostfix(curImageName);
                      tileset.imageName = nameWithPostfix;
                      tileset.sourceImage = this._spriteFrameMap[nameWithPostfix];
                      if (!tileset.sourceImage) {
                        const shortName = TMXMapInfo.getShortName(curImageName);
                        tileset.imageName = shortName;
                        tileset.sourceImage = this._spriteFrameMap[shortName];
                        if (!tileset.sourceImage) {
                          error(`[error]: ${shortName} not find in [${Object.keys(this._spriteFrameMap).join(', ')}]`);
                          errorID(7221, curImageName);
                          warn(`Please try asset type of ${curImageName} to 'sprite-frame'`);
                        }
                      }
                    }
                  }
                  tileset.spacing = tilesetSpacing;
                  tileset.margin = tilesetMargin;
                  tileset._tileSize.width = tilesetSize.width;
                  tileset._tileSize.height = tilesetSize.height;
                  this.setTilesets(tileset);
                }
                tile = tiles && tiles[tileIdx];
                if (!tile) {
                  continue;
                }
                this.parentGID = fgid + (parseInt(tile.getAttribute('id')) || 0);
                const tileImages = tile.getElementsByTagName('image');
                if (tile.hasAttribute('x') && tile.hasAttribute('y')) {
                  tileset.imageOffset = new Vec2(parseFloat(tile.getAttribute('x')) || 0, parseFloat(tile.getAttribute('y')) || 0);
                }
                const hastilesize = tile.hasAttribute('width') && tile.hasAttribute('height');
                if (hastilesize) {
                  tileset._tileSize.width = parseFloat(tile.getAttribute('width')) || 0;
                  tileset._tileSize.height = parseFloat(tile.getAttribute('height')) || 0;
                }
                if (tileImages && tileImages.length > 0) {
                  const image = tileImages[0];
                  let imageName = image.getAttribute('source');
                  imageName = imageName.replace(/\\/g, '/');
                  tileset.imageName = imageName;
                  tileset.imageSize.width = parseFloat(image.getAttribute('width')) || 0;
                  tileset.imageSize.height = parseFloat(image.getAttribute('height')) || 0;
                  if (!hastilesize) {
                    tileset._tileSize.width = tileset.imageSize.width;
                    tileset._tileSize.height = tileset.imageSize.height;
                  }
                  tileset.sourceImage = this._spriteFrameMap[imageName];
                  if (!tileset.sourceImage) {
                    const nameWithPostfix = TMXMapInfo.getNameWithPostfix(imageName);
                    tileset.imageName = nameWithPostfix;
                    tileset.sourceImage = this._spriteFrameMap[nameWithPostfix];
                    if (!tileset.sourceImage) {
                      const shortName = TMXMapInfo.getShortName(imageName);
                      tileset.imageName = shortName;
                      tileset.sourceImage = this._spriteFrameMap[shortName];
                      if (!tileset.sourceImage) {
                        errorID(7221, imageName);
                        warn(`Please try asset type of ${imageName} to 'sprite-frame'`);
                      }
                    }
                  }
                  tileset.firstGid = this.parentGID & 268435455;
                }
                const pid = (268435455 & this.parentGID) >>> 0;
                this._tileProperties.set(pid, getPropertyList(tile));
                const animations = tile.getElementsByTagName('animation');
                if (animations && animations.length > 0) {
                  const animation = animations[0];
                  const framesData = animation.getElementsByTagName('frame');
                  const animationProp = {
                    frames: [],
                    dt: 0,
                    frameIdx: 0
                  };
                  this._tileAnimations.set(pid, animationProp);
                  const frames = animationProp.frames;
                  for (let frameIdx = 0; frameIdx < framesData.length; frameIdx++) {
                    const frame = framesData[frameIdx];
                    const tileid = fgid + (parseInt(frame.getAttribute('tileid')) || 0);
                    const duration = parseFloat(frame.getAttribute('duration')) || 0;
                    frames.push({
                      tileid: tileid,
                      duration: duration / 1000,
                      grid: null
                    });
                  }
                }
              }
            }
          }
          const childNodes = map.childNodes;
          for (i = 0; i < childNodes.length; i++) {
            const childNode = childNodes[i];
            if (this._shouldIgnoreNode(childNode)) {
              continue;
            }
            if (childNode.nodeName === 'imagelayer') {
              const imageLayer = this._parseImageLayer(childNode);
              if (imageLayer) {
                this.setImageLayers(imageLayer);
              }
            }
            if (childNode.nodeName === 'layer') {
              const layer = this._parseLayer(childNode);
              this.setLayers(layer);
            }
            if (childNode.nodeName === 'objectgroup') {
              const objectGroup = this._parseObjectGroup(childNode);
              this.setObjectGroups(objectGroup);
            }
          }
          return map;
        }
        _shouldIgnoreNode(node) {
          return node.nodeType === 3 || node.nodeType === 8 || node.nodeType === 4;
        }
        _parseImageLayer(selLayer) {
          const datas = selLayer.getElementsByTagName('image');
          if (!datas || datas.length === 0) return null;
          const imageLayer = new TMXImageLayerInfo();
          imageLayer.name = selLayer.getAttribute('name');
          imageLayer.offset.x = parseFloat(selLayer.getAttribute('offsetx')) || 0;
          imageLayer.offset.y = parseFloat(selLayer.getAttribute('offsety')) || 0;
          const visible = selLayer.getAttribute('visible');
          imageLayer.visible = !(visible === '0');
          const opacity = selLayer.getAttribute('opacity');
          imageLayer.opacity = opacity ? Math.round(255 * parseFloat(opacity)) : 255;
          const tintColor = selLayer.getAttribute('tintcolor');
          imageLayer.tintColor = tintColor ? strToColor(tintColor) : null;
          const data = datas[0];
          const source = data.getAttribute('source');
          imageLayer.sourceImage = this._imageLayerSPF[source];
          imageLayer.width = parseInt(data.getAttribute('width')) || 0;
          imageLayer.height = parseInt(data.getAttribute('height')) || 0;
          imageLayer.trans = strToColor(data.getAttribute('trans'));
          if (!imageLayer.sourceImage) {
            errorID(7221, source);
            warn(`Please try asset type of ${source} to 'sprite-frame'`);
            return null;
          }
          return imageLayer;
        }
        _parseLayer(selLayer) {
          const data = selLayer.getElementsByTagName('data')[0];
          const layer = new TMXLayerInfo();
          layer.name = selLayer.getAttribute('name');
          const layerSize = new Size$1(0, 0);
          layerSize.width = parseFloat(selLayer.getAttribute('width'));
          layerSize.height = parseFloat(selLayer.getAttribute('height'));
          layer.layerSize = layerSize;
          const visible = selLayer.getAttribute('visible');
          layer.visible = !(visible === '0');
          const opacity = selLayer.getAttribute('opacity');
          if (opacity) layer.opacity = Math.round(255 * parseFloat(opacity));else layer.opacity = 255;
          layer.offset = new Vec2(parseFloat(selLayer.getAttribute('offsetx')) || 0, parseFloat(selLayer.getAttribute('offsety')) || 0);
          const tintColor = selLayer.getAttribute('tintcolor');
          layer.tintColor = tintColor ? strToColor(tintColor) : null;
          let nodeValue = '';
          for (let j = 0; j < data.childNodes.length; j++) {
            nodeValue += data.childNodes[j].nodeValue;
          }
          nodeValue = nodeValue.trim();
          const compression = data.getAttribute('compression');
          const encoding = data.getAttribute('encoding');
          if (compression && compression !== 'gzip' && compression !== 'zlib') {
            logID(7218);
            return null;
          }
          let tiles;
          switch (compression) {
            case 'gzip':
              tiles = codec.unzipBase64AsArray(nodeValue, 4);
              break;
            case 'zlib':
              {
                const inflator = new _p.Inflate(codec.Base64.decodeAsArray(nodeValue, 1));
                tiles = uint8ArrayToUint32Array(inflator.decompress());
                break;
              }
            case null:
            case '':
              if (encoding === 'base64') tiles = codec.Base64.decodeAsArray(nodeValue, 4);else if (encoding === 'csv') {
                tiles = [];
                const csvTiles = nodeValue.split(',');
                for (let csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) tiles.push(parseInt(csvTiles[csvIdx]));
              } else {
                const selDataTiles = data.getElementsByTagName('tile');
                tiles = [];
                for (let xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute('gid')));
              }
              break;
            default:
              if (this.layerAttrs === TMXLayerInfo.ATTRIB_NONE) logID(7219);
              break;
          }
          if (tiles) {
            layer.tiles = new Uint32Array(tiles);
          }
          layer.properties = getPropertyList(selLayer);
          return layer;
        }
        _parseObjectGroup(selGroup) {
          const objectGroup = new TMXObjectGroupInfo();
          objectGroup.name = selGroup.getAttribute('name') || '';
          objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')), parseFloat(selGroup.getAttribute('offsety')));
          const opacity = selGroup.getAttribute('opacity');
          if (opacity) objectGroup.opacity = Math.round(255 * parseFloat(opacity));else objectGroup.opacity = 255;
          const tintColor = selGroup.getAttribute('tintcolor');
          objectGroup.tintColor = tintColor ? strToColor(tintColor) : null;
          const visible = selGroup.getAttribute('visible');
          if (visible && parseInt(visible) === 0) objectGroup.visible = false;
          const color = selGroup.getAttribute('color');
          if (color) objectGroup.color.fromHEX(color);
          const draworder = selGroup.getAttribute('draworder');
          if (draworder) objectGroup.draworder = draworder;
          objectGroup.setProperties(getPropertyList(selGroup));
          const objects = selGroup.getElementsByTagName('object');
          if (objects) {
            for (let j = 0; j < objects.length; j++) {
              const selObj = objects[j];
              const objectProp = {};
              objectProp.id = selObj.getAttribute('id') || j;
              objectProp.name = selObj.getAttribute('name') || '';
              objectProp.width = parseFloat(selObj.getAttribute('width')) || 0;
              objectProp.height = parseFloat(selObj.getAttribute('height')) || 0;
              objectProp.x = parseFloat(selObj.getAttribute('x')) || 0;
              objectProp.y = parseFloat(selObj.getAttribute('y')) || 0;
              objectProp.rotation = parseFloat(selObj.getAttribute('rotation')) || 0;
              objectProp.properties = getPropertyList(selObj);
              const visibleAttr = selObj.getAttribute('visible');
              objectProp.visible = !(visibleAttr && parseInt(visibleAttr) === 0);
              const texts = selObj.getElementsByTagName('text');
              if (texts && texts.length > 0) {
                const text = texts[0];
                objectProp.type = 5;
                objectProp.wrap = text.getAttribute('wrap') === '1';
                objectProp.color = strToColor(text.getAttribute('color'));
                objectProp.halign = strToHAlign(text.getAttribute('halign'));
                objectProp.valign = strToVAlign(text.getAttribute('valign'));
                objectProp.pixelsize = parseInt(text.getAttribute('pixelsize')) || 16;
                objectProp.text = text.childNodes[0].nodeValue;
              }
              const gid = selObj.getAttribute('gid');
              if (gid) {
                objectProp.gid = parseInt(gid);
                objectProp.type = 4;
              }
              const ellipse = selObj.getElementsByTagName('ellipse');
              if (ellipse && ellipse.length > 0) {
                objectProp.type = 1;
              }
              const polygonProps = selObj.getElementsByTagName('polygon');
              if (polygonProps && polygonProps.length > 0) {
                objectProp.type = 2;
                const selPgPointStr = polygonProps[0].getAttribute('points');
                if (selPgPointStr) objectProp.points = this._parsePointsString(selPgPointStr);
              }
              const polylineProps = selObj.getElementsByTagName('polyline');
              if (polylineProps && polylineProps.length > 0) {
                objectProp.type = 3;
                const selPlPointStr = polylineProps[0].getAttribute('points');
                if (selPlPointStr) objectProp.polylinePoints = this._parsePointsString(selPlPointStr);
              }
              if (!objectProp.type) {
                objectProp.type = 0;
              }
              objectGroup.objects.push(objectProp);
            }
            if (draworder !== 'index') {
              objectGroup.objects.sort((a, b) => a.y - b.y);
            }
          }
          return objectGroup;
        }
        _parsePointsString(pointsString) {
          if (!pointsString) return null;
          const points = [];
          const pointsStr = pointsString.split(' ');
          for (let i = 0; i < pointsStr.length; i++) {
            const selPointStr = pointsStr[i].split(',');
            points.push({
              x: parseFloat(selPointStr[0]),
              y: parseFloat(selPointStr[1])
            });
          }
          return points;
        }
        setTileAnimations(animations) {
          this._tileAnimations = animations;
        }
        getTileAnimations() {
          return this._tileAnimations;
        }
        getTileProperties() {
          return this._tileProperties;
        }
        setTileProperties(tileProperties) {
          this._tileProperties = tileProperties;
        }
        getCurrentString() {
          return this.currentString;
        }
        setCurrentString(currentString) {
          this.currentString = currentString;
        }
        static getNameWithPostfix(name) {
          name = name.replace(/\\/g, '/');
          const slashIndex = name.lastIndexOf('/') + 1;
          const strLen = name.length;
          return name.substring(slashIndex, strLen);
        }
        static getShortName(name) {
          name = name.replace(/\\/g, '/');
          const slashIndex = name.lastIndexOf('/') + 1;
          let dotIndex = name.lastIndexOf('.');
          dotIndex = dotIndex < 0 ? name.length : dotIndex;
          return name.substring(slashIndex, dotIndex);
        }
      }

      var _dec$p, _dec2$m, _dec3$k, _dec4$e, _dec5$e, _dec6$8, _dec7$6, _class$p, _class2$l, _initializer$k, _initializer2$i;
      let TiledTile = exports("TiledTile", (_dec$p = ccclass$H('cc.TiledTile'), _dec2$m = requireComponent(UITransform), _dec3$k = type$a(CCInteger), _dec4$e = type$a(CCInteger), _dec5$e = type$a(CCInteger), _dec6$8 = type$a(CCInteger), _dec7$6 = type$a(CCInteger), _dec$p(_class$p = _dec2$m(_class$p = (_class2$l = class TiledTile extends Component {
        constructor() {
          super();
          this._layer = null;
          this._x = _initializer$k && _initializer$k();
          this._y = _initializer2$i && _initializer2$i();
        }
        get x() {
          return this._x;
        }
        set x(value) {
          if (value === this._x) return;
          if (this._layer && this._layer.isInvalidPosition(value, this._y)) {
            warn(`Invalid x, the valid value is between [%s] ~ [%s]`, 0, this._layer.layerSize.width);
            return;
          }
          this._resetTile();
          this._x = value;
          this.updateInfo();
        }
        get y() {
          return this._y;
        }
        set y(value) {
          if (value === this._y) return;
          if (this._layer && this._layer.isInvalidPosition(this._x, value)) {
            warn(`Invalid y, the valid value is between [%s] ~ [%s]`, 0, this._layer.layerSize.height);
            return;
          }
          this._resetTile();
          this._y = value;
          this.updateInfo();
        }
        get grid() {
          if (this._layer) {
            return this._layer.getTileGIDAt(this._x, this._y);
          }
          return 0;
        }
        set grid(value) {
          if (this._layer) {
            this._layer.setTileGIDAt(value, this._x, this._y);
          }
        }
        onEnable() {
          const parent = this.node.parent;
          this._layer = parent.getComponent('cc.TiledLayer');
          this.node.on("transform-changed", this._updatePosition, this);
          this.node.on("size-changed", this._updatePosition, this);
          this._resetTile();
          this.updateInfo();
        }
        onDisable() {
          this._resetTile();
          this.node.off("transform-changed", this._updatePosition, this);
          this.node.off("size-changed", this._updatePosition, this);
        }
        _resetTile() {
          if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) {
            this._layer.setTiledTileAt(this._x, this._y, null);
          }
        }
        updateInfo() {
          if (!this._layer) return;
          const x = this._x;
          const y = this._y;
          if (this._layer.getTiledTileAt(x, y)) {
            warn('There is already a TiledTile at [%s, %s]', x, y);
            return;
          }
          const p = this._layer.getPositionAt(x, y);
          this.node.setPosition(p.x, p.y);
          this._layer.setTiledTileAt(x, y, this);
          this._layer.markForUpdateRenderData();
        }
        _updatePosition() {
          this._layer.markForUpdateRenderData();
        }
      }, (_initializer$k = applyDecoratedInitializer(_class2$l.prototype, "_x", [_dec3$k], function () {
        return 0;
      }), _initializer2$i = applyDecoratedInitializer(_class2$l.prototype, "_y", [_dec4$e], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$l.prototype, "x", [_dec5$e], Object.getOwnPropertyDescriptor(_class2$l.prototype, "x"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "y", [_dec6$8], Object.getOwnPropertyDescriptor(_class2$l.prototype, "y"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "grid", [_dec7$6], Object.getOwnPropertyDescriptor(_class2$l.prototype, "grid"), _class2$l.prototype)), _class2$l)) || _class$p) || _class$p));

      function fillTextureGrids(tileset, texGrids, spFrame) {
        const spf = spFrame || tileset.sourceImage;
        const tex = spf.texture;
        const collection = tileset.collection;
        if (!tileset.imageSize.width || !tileset.imageSize.height) {
          const sourceImage = tileset.sourceImage;
          tileset.imageSize.width = sourceImage.width;
          tileset.imageSize.height = sourceImage.height;
        }
        const imageWidth = tileset.imageSize.width;
        const imageHeight = tileset.imageSize.height;
        const tw = tileset._tileSize.width;
        const th = tileset._tileSize.height;
        const texWidth = spf.width;
        const texHeight = spf.height;
        const spacing = tileset.spacing;
        const margin = tileset.margin;
        let count = 1;
        if (!collection) {
          const cols = Math.floor((imageWidth - margin * 2 + spacing) / (tw + spacing));
          const rows = Math.floor((imageHeight - margin * 2 + spacing) / (th + spacing));
          count = Math.max(1, rows * cols);
        }
        const firstGid = tileset.firstGid;
        let grid = null;
        let override = !!texGrids.get(firstGid);
        const maxGid = tileset.firstGid + count;
        let gid = firstGid;
        for (; gid < maxGid; ++gid) {
          if (override && !texGrids.get(gid)) {
            override = false;
          }
          if (!override && texGrids.get(gid)) {
            break;
          }
          grid = {
            tileset,
            x: 0,
            y: 0,
            width: tw,
            height: th,
            t: 0,
            l: 0,
            r: 0,
            b: 0,
            cx: 0,
            cy: 0,
            offsetX: 0,
            offsetY: 0,
            rotated: false,
            gid: gid,
            spriteFrame: spf,
            texture: tex
          };
          tileset.rectForGID(gid, grid);
          if (!spFrame || count > 1 || tileset.imageOffset) {
            if (spFrame) {
              grid._name = spFrame.name;
              const lm = spFrame.unbiasUV[0];
              const bm = spFrame.rotated ? spFrame.unbiasUV[1] : spFrame.unbiasUV[5];
              grid.l = lm + grid.x / texWidth;
              grid.t = bm + grid.y / texHeight;
              grid.r = lm + (grid.x + grid.width) / texWidth;
              grid.b = bm + (grid.y + grid.height) / texHeight;
              grid._rect = new Rect$1(grid.x, grid.y, grid.width, grid.height);
            } else {
              grid.l = grid.x / texWidth;
              grid.t = grid.y / texHeight;
              grid.r = (grid.x + grid.width) / texWidth;
              grid.b = (grid.y + grid.height) / texHeight;
              grid._rect = new Rect$1(grid.x, grid.y, grid.width, grid.height);
            }
          } else if (spFrame.rotated) {
            grid._rotated = true;
            grid._name = spFrame.name;
            grid._rect = spFrame.getRect();
            grid.l = spFrame.unbiasUV[0];
            grid.t = spFrame.unbiasUV[1];
            grid.r = spFrame.unbiasUV[4];
            grid.b = spFrame.unbiasUV[3];
          } else {
            grid._name = spFrame.name;
            grid._rect = spFrame.getRect();
            grid.l = spFrame.unbiasUV[0];
            grid.t = spFrame.unbiasUV[5];
            grid.r = spFrame.unbiasUV[2];
            grid.b = spFrame.unbiasUV[1];
          }
          grid.cx = (grid.l + grid.r) / 2;
          grid.cy = (grid.t + grid.b) / 2;
          texGrids.set(gid, grid);
        }
      }

      var _dec$o, _class$o, _dec2$l, _class3$e;
      const _mat4_temp$3 = new Mat4();
      const _vec2_temp = new Vec2();
      const _vec3_temp = new Vec3();
      const _vec3_temp2 = new Vec3();
      const _tempRowCol = {
        row: 0,
        col: 0
      };
      let TiledUserNodeData = exports("TiledUserNodeData", (_dec$o = ccclass$H('cc.TiledUserNodeData'), _dec$o(_class$o = class TiledUserNodeData extends Component {
        constructor() {
          super();
          this._index = -1;
          this._row = -1;
          this._col = -1;
          this._tiledLayer = null;
        }
      }) || _class$o));
      let TiledLayer = exports("TiledLayer", (_dec2$l = ccclass$H('cc.TiledLayer'), _dec2$l(_class3$e = class TiledLayer extends UIRenderer {
        get cullingRect() {
          return this._cullingRect;
        }
        get rightTop() {
          return this._rightTop;
        }
        get layerSize() {
          return this._layerSize;
        }
        get tiledDataArray() {
          return this._tiledDataArray;
        }
        get leftDownToCenterX() {
          return this._leftDownToCenterX;
        }
        get leftDownToCenterY() {
          return this._leftDownToCenterY;
        }
        requestDrawInfo(idx) {
          if (!this._drawInfoList[idx]) {
            this._drawInfoList[idx] = new RenderDrawInfo();
            this._drawInfoList[idx].setDrawInfoType(2);
          }
          return this._drawInfoList[idx];
        }
        constructor() {
          super();
          this._userNodeGrid = {};
          this._userNodeMap = {};
          this._userNodeDirty = false;
          this.tiledTiles = [];
          this._viewPort = {
            x: -1,
            y: -1,
            width: -1,
            height: -1
          };
          this._cullingRect = {
            leftDown: {
              row: -1,
              col: -1
            },
            rightTop: {
              row: -1,
              col: -1
            }
          };
          this._cullingDirty = true;
          this._rightTop = {
            row: -1,
            col: -1
          };
          this._layerInfo = null;
          this._mapInfo = null;
          this._topOffset = 0;
          this._downOffset = 0;
          this._leftOffset = 0;
          this._rightOffset = 0;
          this.tiles = [];
          this.vertices = [];
          this._verticesDirty = true;
          this._layerName = '';
          this._layerSize = void 0;
          this._minGID = void 0;
          this._maxGID = void 0;
          this._layerOrientation = null;
          this._opacity = void 0;
          this._tintColor = void 0;
          this.texGrids = null;
          this._textures = [];
          this._tilesets = [];
          this._leftDownToCenterX = 0;
          this._leftDownToCenterY = 0;
          this._hasTiledNodeGrid = false;
          this._hasAniGrid = false;
          this._animations = null;
          this._enableCulling = void 0;
          this.colorChanged = false;
          this._properties = void 0;
          this.renderOrder = void 0;
          this._staggerAxis = void 0;
          this._staggerIndex = void 0;
          this._hexSideLength = void 0;
          this._mapTileSize = void 0;
          this._odd_even = void 0;
          this._diffX1 = void 0;
          this._diffY1 = void 0;
          this._useAutomaticVertexZ = void 0;
          this._vertexZvalue = void 0;
          this._offset = void 0;
          this._tiledDataArray = [];
          this._cameraNode = void 0;
          this._drawInfoList = [];
          this._tiledDataArrayIdx = 0;
        }
        hasTiledNode() {
          return this._hasTiledNodeGrid;
        }
        hasAnimation() {
          return this._hasAniGrid;
        }
        set enableCulling(value) {
          if (this._enableCulling !== value) {
            this._enableCulling = value;
            this._cullingDirty = true;
            this.markForUpdateRenderData();
          }
        }
        get enableCulling() {
          return this._enableCulling;
        }
        addUserNode(node) {
          let dataComp = node.getComponent(TiledUserNodeData);
          if (dataComp) {
            warn('CCTiledLayer:addUserNode node has been added');
            return false;
          }
          dataComp = node.addComponent(TiledUserNodeData);
          node.parent = this.node;
          this._userNodeMap[node.uuid] = dataComp;
          dataComp._row = -1;
          dataComp._col = -1;
          dataComp._tiledLayer = this;
          this._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
          this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
          this._addUserNodeToGrid(dataComp, _tempRowCol);
          this._updateCullingOffsetByUserNode(node);
          node.on("transform-changed", this._userNodePosChange, dataComp);
          node.on("size-changed", this._userNodeSizeChange, dataComp);
          return true;
        }
        removeUserNode(node) {
          const dataComp = node.getComponent(TiledUserNodeData);
          if (!dataComp) {
            warn('CCTiledLayer:removeUserNode node is not exist');
            return false;
          }
          node.off("transform-changed", this._userNodePosChange, dataComp);
          node.off("size-changed", this._userNodeSizeChange, dataComp);
          this._removeUserNodeFromGrid(dataComp);
          delete this._userNodeMap[node.uuid];
          node._removeComponent(dataComp);
          dataComp.destroy();
          node.removeFromParent();
          return true;
        }
        destroyUserNode(node) {
          this.removeUserNode(node);
          node.destroy();
        }
        _nodeLocalPosToLayerPos(nodePos, out) {
          out.x = nodePos.x + this._leftDownToCenterX;
          out.y = nodePos.y + this._leftDownToCenterY;
        }
        getNodesByRowCol(row, col) {
          const rowData = this._userNodeGrid[row];
          if (!rowData) return null;
          return rowData[col];
        }
        getNodesCountByRow(row) {
          const rowData = this._userNodeGrid[row];
          if (!rowData) return 0;
          return rowData.count;
        }
        _updateAllUserNode() {
          this._userNodeGrid = {};
          for (const dataId in this._userNodeMap) {
            const dataComp = this._userNodeMap[dataId];
            this._nodeLocalPosToLayerPos(dataComp.node.getPosition(), _vec2_temp);
            this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
            this._addUserNodeToGrid(dataComp, _tempRowCol);
            this._updateCullingOffsetByUserNode(dataComp.node);
          }
        }
        _updateCullingOffsetByUserNode(node_) {
          const node = node_._uiProps.uiTransformComp.contentSize;
          if (this._topOffset < node.height) {
            this._topOffset = node.height;
          }
          if (this._downOffset < node.height) {
            this._downOffset = node.height;
          }
          if (this._leftOffset < node.width) {
            this._leftOffset = node.width;
          }
          if (this._rightOffset < node.width) {
            this._rightOffset = node.width;
          }
        }
        _userNodeSizeChange() {
          const dataComp = this;
          const node = dataComp.node;
          const self = dataComp._tiledLayer;
          self._updateCullingOffsetByUserNode(node);
          self._userNodeDirty = true;
          self.markForUpdateRenderData();
        }
        _userNodePosChange() {
          const dataComp = this;
          const node = dataComp.node;
          const self = dataComp._tiledLayer;
          self._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
          self._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
          self._limitInLayer(_tempRowCol);
          if (_tempRowCol.row === dataComp._row && _tempRowCol.col === dataComp._col) return;
          self._removeUserNodeFromGrid(dataComp);
          self._addUserNodeToGrid(dataComp, _tempRowCol);
        }
        _removeUserNodeFromGrid(dataComp) {
          const row = dataComp._row;
          const col = dataComp._col;
          const index = dataComp._index;
          const rowData = this._userNodeGrid[row];
          const colData = rowData && rowData[col];
          if (colData) {
            rowData.count--;
            colData.count--;
            colData.list[index] = null;
            if (colData.count <= 0) {
              colData.list.length = 0;
              colData.count = 0;
            }
          }
          dataComp._row = -1;
          dataComp._col = -1;
          dataComp._index = -1;
          this._userNodeDirty = true;
          this.markForUpdateRenderData();
        }
        _limitInLayer(rowCol) {
          const row = rowCol.row;
          const col = rowCol.col;
          if (row < 0) rowCol.row = 0;
          if (row > this._rightTop.row) rowCol.row = this._rightTop.row;
          if (col < 0) rowCol.col = 0;
          if (col > this._rightTop.col) rowCol.col = this._rightTop.col;
        }
        _addUserNodeToGrid(dataComp, tempRowCol) {
          const row = tempRowCol.row;
          const col = tempRowCol.col;
          const rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || {
            count: 0
          };
          const colData = rowData[col] = rowData[col] || {
            count: 0,
            list: []
          };
          dataComp._row = row;
          dataComp._col = col;
          dataComp._index = colData.list.length;
          rowData.count++;
          colData.count++;
          colData.list.push(dataComp);
          this._userNodeDirty = true;
          this.markForUpdateRenderData();
        }
        isUserNodeDirty() {
          return this._userNodeDirty;
        }
        setUserNodeDirty(value) {
          this._userNodeDirty = value;
        }
        _reinstallCamera() {
          const camera = director.root.batcher2D.getFirstRenderCamera(this.node);
          const cameraNode = camera === null || camera === void 0 ? void 0 : camera.node;
          if (this._cameraNode !== cameraNode) {
            this._uninstallCamera();
            if (cameraNode) {
              cameraNode.on("transform-changed", this.updateCulling, this);
              cameraNode.on("size-changed", this.updateCulling, this);
              this._cameraNode = cameraNode;
            }
          }
          return camera;
        }
        _uninstallCamera() {
          if (this._cameraNode) {
            this._cameraNode.off("transform-changed", this.updateCulling, this);
            this._cameraNode.off("size-changed", this.updateCulling, this);
            delete this._cameraNode;
          }
        }
        onEnable() {
          super.onEnable();
          this.node.on("anchor-changed", this._syncAnchorPoint, this);
          this.node.on("transform-changed", this.updateCulling, this);
          this.node.on("size-changed", this.updateCulling, this);
          this.node.parent.on("transform-changed", this.updateCulling, this);
          this.node.parent.on("size-changed", this.updateCulling, this);
          this.markForUpdateRenderData();
          this.scheduleOnce(this.updateCulling.bind(this));
        }
        onDisable() {
          var _this$node$parent, _this$node$parent2;
          super.onDisable();
          (_this$node$parent = this.node.parent) === null || _this$node$parent === void 0 ? void 0 : _this$node$parent.off("size-changed", this.updateCulling, this);
          (_this$node$parent2 = this.node.parent) === null || _this$node$parent2 === void 0 ? void 0 : _this$node$parent2.off("transform-changed", this.updateCulling, this);
          this.node.off("size-changed", this.updateCulling, this);
          this.node.off("transform-changed", this.updateCulling, this);
          this.node.off("anchor-changed", this._syncAnchorPoint, this);
          this._uninstallCamera();
        }
        _syncAnchorPoint() {
          const node = this.node;
          const trans = node._uiProps.uiTransformComp;
          const scale = node.getScale();
          this._leftDownToCenterX = trans.width * trans.anchorX * scale.x;
          this._leftDownToCenterY = trans.height * trans.anchorY * scale.y;
          this._cullingDirty = true;
          this.markForUpdateRenderData();
        }
        getLayerName() {
          return this._layerName;
        }
        setLayerName(layerName) {
          this._layerName = layerName;
        }
        getProperty(propertyName) {
          return this._properties[propertyName];
        }
        getPositionAt(pos, y) {
          let x;
          if (y !== undefined) {
            x = Math.floor(pos);
            y = Math.floor(y);
          } else {
            x = Math.floor(pos.x);
            y = Math.floor(pos.y);
          }
          switch (this._layerOrientation) {
            case 0:
              return this._positionForOrthoAt(x, y);
            case 2:
              return this._positionForIsoAt(x, y);
            case 1:
              return this._positionForHexAt(x, y);
          }
          return null;
        }
        isInvalidPosition(x, y) {
          return x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0;
        }
        _positionForIsoAt(x, y) {
          let offsetX = 0;
          let offsetY = 0;
          const index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          const gidAndFlags = this.tiles[index];
          if (gidAndFlags) {
            const gid = (gidAndFlags & 268435455) >>> 0;
            const tileset = this.texGrids.get(gid).tileset;
            const offset = tileset.tileOffset;
            offsetX = offset.x;
            offsetY = offset.y;
          }
          return new Vec2(this._mapTileSize.width * 0.5 * (this._layerSize.height + x - y - 1) + offsetX, this._mapTileSize.height * 0.5 * (this._layerSize.width - x + this._layerSize.height - y - 2) - offsetY);
        }
        _positionForOrthoAt(x, y) {
          let offsetX = 0;
          let offsetY = 0;
          const index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          const gidAndFlags = this.tiles[index];
          if (gidAndFlags) {
            const gid = (gidAndFlags & 268435455) >>> 0;
            const tileset = this.texGrids.get(gid).tileset;
            const offset = tileset.tileOffset;
            offsetX = offset.x;
            offsetY = offset.y;
          }
          return new Vec2(x * this._mapTileSize.width + offsetX, (this._layerSize.height - y - 1) * this._mapTileSize.height - offsetY);
        }
        _positionForHexAt(col, row) {
          const tileWidth = this._mapTileSize.width;
          const tileHeight = this._mapTileSize.height;
          const rows = this._layerSize.height;
          const index = Math.floor(col) + Math.floor(row) * this._layerSize.width;
          const gid = (this.tiles[index] & 268435455) >>> 0;
          let offset;
          if (this.texGrids.get(gid)) {
            offset = this.texGrids.get(gid).tileset.tileOffset;
          } else {
            offset = {
              x: 0,
              y: 0
            };
          }
          const odd_even = this._staggerIndex === 0 ? 1 : -1;
          let x = 0;
          let y = 0;
          let diffX = 0;
          let diffY = 0;
          switch (this._staggerAxis) {
            case 1:
              diffX = 0;
              if (row % 2 === 1) {
                diffX = tileWidth / 2 * odd_even;
              }
              x = col * tileWidth + diffX + offset.x;
              y = (rows - row - 1) * (tileHeight - (tileHeight - this._hexSideLength) / 2) - offset.y;
              break;
            case 0:
              diffY = 0;
              if (col % 2 === 1) {
                diffY = tileHeight / 2 * -odd_even;
              }
              x = col * (tileWidth - (tileWidth - this._hexSideLength) / 2) + offset.x;
              y = (rows - row - 1) * tileHeight + diffY - offset.y;
              break;
          }
          return new Vec2(x, y);
        }
        setTilesGIDAt(gids, beginCol, beginRow, totalCols) {
          if (!gids || gids.length === 0 || totalCols <= 0) return;
          if (beginRow < 0) beginRow = 0;
          if (beginCol < 0) beginCol = 0;
          let gidsIdx = 0;
          const endCol = beginCol + totalCols;
          for (let row = beginRow;; row++) {
            for (let col = beginCol; col < endCol; col++) {
              if (gidsIdx >= gids.length) return;
              this._updateTileForGID(gids[gidsIdx], col, row);
              gidsIdx++;
            }
          }
        }
        setTileGIDAt(gid, x, y, flags) {
          const ugid = (gid & 268435455) >>> 0;
          x = Math.floor(x);
          y = Math.floor(y);
          if (this.isInvalidPosition(x, y)) {
            throw new Error('cc.TiledLayer.setTileGIDAt(): invalid position');
          }
          if (!this.tiles || !this._tilesets || this._tilesets.length === 0) {
            logID(7238);
            return;
          }
          if (ugid !== 0 && ugid < this._tilesets[0].firstGid) {
            logID(7239, gid);
            return;
          }
          flags = flags || 0;
          this._updateTileForGID((ugid | flags) >>> 0, x, y);
        }
        _updateTileForGID(gidAndFlags, x, y) {
          const idx = 0 | x + y * this._layerSize.width;
          if (idx >= this.tiles.length) return;
          const oldGIDAndFlags = this.tiles[idx];
          if (gidAndFlags === oldGIDAndFlags) return;
          const gid = (gidAndFlags & 268435455) >>> 0;
          const grid = this.texGrids.get(gid);
          if (grid) {
            this.tiles[idx] = gidAndFlags;
            this._updateVertex(x, y);
          } else {
            this.tiles[idx] = 0;
          }
          this._cullingDirty = true;
        }
        getTileGIDAt(x, y) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position');
          }
          if (!this.tiles) {
            logID(7237);
            return null;
          }
          const index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          const tile = this.tiles[index];
          return (tile & 268435455) >>> 0;
        }
        getTileFlagsAt(x, y) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.getTileFlagsAt: invalid position');
          }
          if (!this.tiles) {
            logID(7240);
            return null;
          }
          const idx = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          const tile = this.tiles[idx];
          return (tile & 4026531840) >>> 0;
        }
        setCullingDirty(value) {
          this._cullingDirty = value;
        }
        isCullingDirty() {
          return this._cullingDirty;
        }
        updateViewPort(x, y, width, height) {
          if (this._viewPort.width === width && this._viewPort.height === height && this._viewPort.x === x && this._viewPort.y === y) {
            return;
          }
          this._viewPort.x = x;
          this._viewPort.y = y;
          this._viewPort.width = width;
          this._viewPort.height = height;
          let reserveLine = 1;
          if (this._layerOrientation === 2) {
            reserveLine = 2;
          }
          const vpx = this._viewPort.x - this._offset.x + this._leftDownToCenterX;
          const vpy = this._viewPort.y - this._offset.y + this._leftDownToCenterY;
          let leftDownX = vpx - this._leftOffset;
          let leftDownY = vpy - this._downOffset;
          const rightTopX = vpx + width + this._rightOffset;
          const rightTopY = vpy + height + this._topOffset;
          const leftDown = this._cullingRect.leftDown;
          const rightTop = this._cullingRect.rightTop;
          if (leftDownX < 0) leftDownX = 0;
          if (leftDownY < 0) leftDownY = 0;
          this._positionToRowCol(leftDownX, leftDownY, _tempRowCol);
          _tempRowCol.row -= reserveLine;
          _tempRowCol.col -= reserveLine;
          _tempRowCol.row = _tempRowCol.row > 0 ? _tempRowCol.row : 0;
          _tempRowCol.col = _tempRowCol.col > 0 ? _tempRowCol.col : 0;
          if (_tempRowCol.row !== leftDown.row || _tempRowCol.col !== leftDown.col) {
            leftDown.row = _tempRowCol.row;
            leftDown.col = _tempRowCol.col;
            this._cullingDirty = true;
          }
          if (rightTopX < 0 || rightTopY < 0) {
            _tempRowCol.row = -1;
            _tempRowCol.col = -1;
          } else {
            this._positionToRowCol(rightTopX, rightTopY, _tempRowCol);
            _tempRowCol.row++;
            _tempRowCol.col++;
          }
          if (_tempRowCol.row !== rightTop.row || _tempRowCol.col !== rightTop.col) {
            rightTop.row = _tempRowCol.row;
            rightTop.col = _tempRowCol.col;
            this._cullingDirty = true;
          }
          if (this._cullingDirty) this.markForUpdateRenderData();
        }
        _positionToRowCol(x, y, result) {
          const maptw = this._mapTileSize.width;
          const mapth = this._mapTileSize.height;
          const maptw2 = maptw * 0.5;
          const mapth2 = mapth * 0.5;
          let row = 0;
          let col = 0;
          let diffX2 = 0;
          let diffY2 = 0;
          const axis = this._staggerAxis;
          switch (this._layerOrientation) {
            case 0:
              col = Math.floor(x / maptw);
              row = Math.floor(y / mapth);
              break;
            case 2:
              col = Math.floor(x / maptw2);
              row = Math.floor(y / mapth2);
              break;
            case 1:
              if (axis === 1) {
                row = Math.floor(y / (mapth - this._diffY1));
                diffX2 = row % 2 === 1 ? maptw2 * this._odd_even : 0;
                col = Math.floor((x - diffX2) / maptw);
              } else {
                col = Math.floor(x / (maptw - this._diffX1));
                diffY2 = col % 2 === 1 ? mapth2 * -this._odd_even : 0;
                row = Math.floor((y - diffY2) / mapth);
              }
              break;
          }
          result.row = row;
          result.col = col;
          return result;
        }
        updateCulling() {
          if (this._enableCulling) {
            this.node.updateWorldTransform();
            Mat4.invert(_mat4_temp$3, this.node.getWorldMatrix());
            const camera = this._reinstallCamera();
            if (camera) {
              _vec3_temp.x = 0;
              _vec3_temp.y = 0;
              _vec3_temp.z = 0;
              _vec3_temp2.x = camera.width;
              _vec3_temp2.y = camera.height;
              _vec3_temp2.z = 0;
              camera.screenToWorld(_vec3_temp, _vec3_temp);
              camera.screenToWorld(_vec3_temp2, _vec3_temp2);
              Vec3.transformMat4(_vec3_temp, _vec3_temp, _mat4_temp$3);
              Vec3.transformMat4(_vec3_temp2, _vec3_temp2, _mat4_temp$3);
              this.updateViewPort(_vec3_temp.x, _vec3_temp.y, _vec3_temp2.x - _vec3_temp.x, _vec3_temp2.y - _vec3_temp.y);
            }
          }
        }
        getLayerOrientation() {
          return this._layerOrientation;
        }
        getProperties() {
          return this._properties;
        }
        _updateVertex(col, row) {
          const FLIPPED_MASK = 268435455;
          const vertices = this.vertices;
          const layerOrientation = this._layerOrientation;
          const tiles = this.tiles;
          if (!tiles) {
            return;
          }
          const rightTop = this._rightTop;
          const maptw = this._mapTileSize.width;
          const mapth = this._mapTileSize.height;
          const maptw2 = maptw * 0.5;
          const mapth2 = mapth * 0.5;
          const rows = this._layerSize.height;
          const cols = this._layerSize.width;
          const grids = this.texGrids;
          let left = 0;
          let bottom = 0;
          let axis;
          let diffX1;
          let diffY1;
          let odd_even;
          let diffX2;
          let diffY2;
          if (layerOrientation === 1) {
            axis = this._staggerAxis;
            diffX1 = this._diffX1;
            diffY1 = this._diffY1;
            odd_even = this._odd_even;
          }
          let cullingCol = 0;
          let cullingRow = 0;
          let gridGID = 0;
          let topBorder = 0;
          let downBorder = 0;
          let leftBorder = 0;
          let rightBorder = 0;
          const index = row * cols + col;
          const gid = tiles[index];
          gridGID = (gid & FLIPPED_MASK) >>> 0;
          const grid = grids.get(gridGID);
          if (!grid) {
            return;
          }
          if (this._animations.get(gridGID)) {
            this._hasAniGrid = this._hasAniGrid || true;
          }
          switch (layerOrientation) {
            case 0:
              cullingCol = col;
              cullingRow = rows - row - 1;
              left = cullingCol * maptw;
              bottom = cullingRow * mapth;
              break;
            case 2:
              cullingCol = rows + col - row - 1;
              cullingRow = rows + cols - col - row - 2;
              left = maptw2 * cullingCol;
              bottom = mapth2 * cullingRow;
              break;
            case 1:
              diffX2 = axis === 1 && row % 2 === 1 ? maptw2 * odd_even : 0;
              diffY2 = axis === 0 && col % 2 === 1 ? mapth2 * -odd_even : 0;
              left = col * (maptw - diffX1) + diffX2;
              bottom = (rows - row - 1) * (mapth - diffY1) + diffY2;
              cullingCol = col;
              cullingRow = rows - row - 1;
              break;
          }
          const rowData = vertices[cullingRow] = vertices[cullingRow] || {
            minCol: 0,
            maxCol: 0
          };
          const colData = rowData[cullingCol] = rowData[cullingCol] || {
            left: 0,
            bottom: 0,
            index: 0
          };
          if (rowData.minCol > cullingCol) {
            rowData.minCol = cullingCol;
          }
          if (rowData.maxCol < cullingCol) {
            rowData.maxCol = cullingCol;
          }
          if (rightTop.row < cullingRow) {
            rightTop.row = cullingRow;
            if (layerOrientation === 2) {
              rightTop.row += 1;
            }
          }
          if (rightTop.col < cullingCol) {
            rightTop.col = cullingCol;
            if (layerOrientation === 2) {
              rightTop.col += 1;
            }
          }
          const tileOffset = grid.tileset.tileOffset;
          left += this._offset.x + tileOffset.x + grid.offsetX;
          bottom += this._offset.y - tileOffset.y - grid.offsetY;
          topBorder = -tileOffset.y + grid.tileset._tileSize.height - mapth;
          topBorder = topBorder < 0 ? 0 : topBorder;
          downBorder = tileOffset.y < 0 ? 0 : tileOffset.y;
          leftBorder = -tileOffset.x < 0 ? 0 : -tileOffset.x;
          rightBorder = tileOffset.x + grid.tileset._tileSize.width - maptw;
          rightBorder = rightBorder < 0 ? 0 : rightBorder;
          if (this._rightOffset < leftBorder) {
            this._rightOffset = leftBorder;
          }
          if (this._leftOffset < rightBorder) {
            this._leftOffset = rightBorder;
          }
          if (this._topOffset < downBorder) {
            this._topOffset = downBorder;
          }
          if (this._downOffset < topBorder) {
            this._downOffset = topBorder;
          }
          colData.left = left;
          colData.bottom = bottom;
          colData.index = index;
          this._cullingDirty = true;
        }
        _updateVertices() {
          const vertices = this.vertices;
          vertices.length = 0;
          const tiles = this.tiles;
          if (!tiles) {
            return;
          }
          const rightTop = this._rightTop;
          rightTop.row = -1;
          rightTop.col = -1;
          const rows = this._layerSize.height;
          const cols = this._layerSize.width;
          this._topOffset = 0;
          this._downOffset = 0;
          this._leftOffset = 0;
          this._rightOffset = 0;
          this._hasAniGrid = false;
          for (let row = 0; row < rows; ++row) {
            for (let col = 0; col < cols; ++col) {
              this._updateVertex(col, row);
            }
          }
          this._verticesDirty = false;
        }
        getTiledTileAt(x, y, forceCreate) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.getTiledTileAt: invalid position');
          }
          if (!this.tiles) {
            logID(7236);
            return null;
          }
          const index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          let tile = this.tiledTiles[index];
          if (!tile && forceCreate) {
            const node = new Node$1();
            tile = node.addComponent(TiledTile);
            tile._x = x;
            tile._y = y;
            tile._layer = this;
            tile.updateInfo();
            node.parent = this.node;
            return tile;
          }
          return tile;
        }
        setTiledTileAt(x, y, tiledTile) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.setTiledTileAt: invalid position');
          }
          if (!this.tiles) {
            logID(7236);
            return null;
          }
          const index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          this.tiledTiles[index] = tiledTile;
          this._cullingDirty = true;
          if (tiledTile) {
            this._hasTiledNodeGrid = true;
          } else {
            this._hasTiledNodeGrid = this.tiledTiles.some(tiledNode => !!tiledNode);
          }
          return tiledTile;
        }
        getTexture(index) {
          index = index || 0;
          if (this._textures && index >= 0 && this._textures.length > index) {
            return this._textures[index];
          }
          return null;
        }
        getTextures() {
          return this._textures;
        }
        setTexture(texture) {
          this.setTextures([texture]);
        }
        setTextures(textures) {
          this._textures = textures;
          this.markForUpdateRenderData();
        }
        getLayerSize() {
          return this._layerSize;
        }
        getMapTileSize() {
          return this._mapTileSize;
        }
        getTileSet(index) {
          index = index || 0;
          if (this._tilesets && index >= 0 && this._tilesets.length > index) {
            return this._tilesets[index];
          }
          return null;
        }
        getTileSets() {
          return this._tilesets;
        }
        setTileSet(tileset) {
          this.setTileSets([tileset]);
        }
        setTileSets(tilesets) {
          this._tilesets = tilesets;
          const textures = this._textures = [];
          const texGrids = this.texGrids;
          texGrids.clear();
          for (let i = 0; i < tilesets.length; i++) {
            const tileset = tilesets[i];
            if (tileset) {
              textures[i] = tileset.sourceImage;
            }
          }
          for (let i = 0, l = tilesets.length; i < l; ++i) {
            const tilesetInfo = tilesets[i];
            if (!tilesetInfo) continue;
            fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
          }
          this._prepareToRender();
        }
        init(layerInfo, mapInfo, tilesets, textures, texGrids) {
          this._cullingDirty = true;
          this._layerInfo = layerInfo;
          this._mapInfo = mapInfo;
          const size = layerInfo.layerSize;
          this._layerName = layerInfo.name;
          this.tiles = layerInfo.tiles;
          this._properties = layerInfo.properties;
          this._layerSize = size;
          this._minGID = layerInfo.minGID;
          this._maxGID = layerInfo.maxGID;
          this._opacity = layerInfo.opacity;
          if (layerInfo.tintColor) {
            this._tintColor = layerInfo.tintColor;
          }
          this.renderOrder = mapInfo.renderOrder;
          this._staggerAxis = mapInfo.getStaggerAxis();
          this._staggerIndex = mapInfo.getStaggerIndex();
          this._hexSideLength = mapInfo.getHexSideLength();
          this._animations = mapInfo.getTileAnimations();
          this._tilesets = tilesets;
          this._textures = textures;
          this.texGrids = texGrids;
          this._layerOrientation = mapInfo.orientation;
          this._mapTileSize = mapInfo.getTileSize();
          const maptw = this._mapTileSize.width;
          const mapth = this._mapTileSize.height;
          const layerW = this._layerSize.width;
          const layerH = this._layerSize.height;
          if (this._layerOrientation === 1) {
            let width = 0;
            let height = 0;
            const tileWidth = maptw & ~1;
            const tileHeight = mapth & ~1;
            this._odd_even = this._staggerIndex === 0 ? 1 : -1;
            if (this._staggerAxis === 0) {
              this._diffX1 = (tileWidth - this._hexSideLength) / 2;
              this._diffY1 = 0;
              width = (this._diffX1 + this._hexSideLength) * layerW + this._diffX1;
              height = tileHeight * layerH + tileHeight / 2;
            } else {
              this._diffX1 = 0;
              this._diffY1 = (tileHeight - this._hexSideLength) / 2;
              width = tileWidth * layerW + tileWidth / 2;
              height = (this._diffY1 + this._hexSideLength) * layerH + this._diffY1;
            }
            this.node._uiProps.uiTransformComp.setContentSize(width, height);
          } else if (this._layerOrientation === 2) {
            const wh = layerW + layerH;
            this.node._uiProps.uiTransformComp.setContentSize(maptw * 0.5 * wh, mapth * 0.5 * wh);
          } else {
            this.node._uiProps.uiTransformComp.setContentSize(layerW * maptw, layerH * mapth);
          }
          this._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
          this._useAutomaticVertexZ = false;
          this._vertexZvalue = 0;
          this._syncAnchorPoint();
          this._prepareToRender();
        }
        _prepareToRender() {
          this._updateVertices();
          this._updateAllUserNode();
        }
        requestTiledRenderData() {
          const arr = this._tiledDataArray;
          while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
            arr.pop();
          }
          if (arr.length > 0) {
            const last = arr[arr.length - 1];
            if (last.renderData && last.renderData.vertexCount === 0) {
              return last;
            }
          }
          const comb = {
            renderData: null,
            texture: null
          };
          this._tiledDataArray.push(comb);
          return comb;
        }
        requestSubNodesData() {
          const arr = this._tiledDataArray;
          if (arr.length > 0) {
            if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
              return arr[arr.length - 1];
            }
          }
          const renderData = [];
          const comb = {
            subNodes: renderData
          };
          this._tiledDataArray.push(comb);
          return comb;
        }
        destroyRenderData() {
          this._tiledDataArray.forEach(rd => {
            const renderData = rd.renderData;
            if (renderData) RenderData.remove(renderData);
          });
          this._tiledDataArray.length = 0;
          super.destroyRenderData();
        }
        _flushAssembler() {
          const assembler = TiledLayer.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
            this._assembler.createData(this);
          }
          if (this._tiledDataArray.length === 0) {
            this.markForUpdateRenderData();
            this._updateColor();
          }
        }
        _render(ui) {
          for (let i = 0; i < this._tiledDataArray.length; i++) {
            this._tiledDataArrayIdx = i;
            const m = this._tiledDataArray[i];
            if (m.subNodes) {
              m.subNodes.forEach(c => {
                if (c) ui.walk(c.node);
              });
            } else {
              const td = m;
              if (td.texture) {
                ui.commitComp(this, td.renderData, td.texture, this._assembler, null);
              }
            }
          }
          this.node._static = true;
        }
        createRenderEntity() {
          return new RenderEntity(2);
        }
        fillIndicesBuffer(renderData, drawInfo) {
          const iBuf = renderData.chunk.meshBuffer.iData;
          let indexOffset = renderData.chunk.meshBuffer.indexOffset;
          drawInfo.setIndexOffset(indexOffset);
          let vertexId = renderData.chunk.vertexOffset;
          const quadCount = renderData.vertexCount / 4;
          for (let i = 0; i < quadCount; i += 1) {
            iBuf[indexOffset] = vertexId;
            iBuf[indexOffset + 1] = vertexId + 1;
            iBuf[indexOffset + 2] = vertexId + 2;
            iBuf[indexOffset + 3] = vertexId + 2;
            iBuf[indexOffset + 4] = vertexId + 1;
            iBuf[indexOffset + 5] = vertexId + 3;
            indexOffset += 6;
            vertexId += 4;
          }
          renderData.chunk.meshBuffer.indexOffset = indexOffset;
          drawInfo.setIBCount(quadCount * 6);
        }
        prepareDrawData() {
          this._drawInfoList.length = 0;
          const entity = this.renderEntity;
          entity.clearDynamicRenderDrawInfos();
          const tiledDataArray = this._tiledDataArray;
          let idx = 0;
          tiledDataArray.forEach(m => {
            if (m.subNodes) {
              m.subNodes.forEach(c => {
                if (c) {
                  if (!this._drawInfoList[idx]) {
                    this._drawInfoList[idx] = new RenderDrawInfo();
                  }
                  const drawInfo = this._drawInfoList[idx];
                  drawInfo.setDrawInfoType(3);
                  drawInfo.setSubNode(c.node);
                  entity.setDynamicRenderDrawInfo(drawInfo, idx);
                  idx++;
                }
              });
            } else {
              const td = m;
              if (td.texture) {
                if (!this._drawInfoList[idx]) {
                  this._drawInfoList[idx] = new RenderDrawInfo();
                }
                const drawInfo = this._drawInfoList[idx];
                td.renderData.fillDrawInfoAttributes(drawInfo);
                drawInfo.setTexture(td.texture.getGFXTexture());
                drawInfo.setSampler(td.texture.getGFXSampler());
                drawInfo.setMaterial(this.getRenderMaterial(0));
                this.fillIndicesBuffer(td.renderData, drawInfo);
                entity.setDynamicRenderDrawInfo(drawInfo, idx);
                idx++;
              }
            }
          });
        }
      }) || _class3$e));

      var _dec$n, _dec2$k, _dec3$j, _class$n, _class2$k;
      let TiledObjectGroup = exports("TiledObjectGroup", (_dec$n = ccclass$H('cc.TiledObjectGroup'), _dec2$k = requireComponent(UITransform), _dec3$j = type$a(CCBoolean), _dec$n(_class$n = _dec2$k(_class$n = (_class2$k = class TiledObjectGroup extends Component {
        constructor() {
          super();
          this._premultiplyAlpha = false;
          this._groupName = void 0;
          this._positionOffset = void 0;
          this._mapInfo = void 0;
          this._properties = void 0;
          this._offset = void 0;
          this._opacity = void 0;
          this._tintColor = null;
          this._animations = void 0;
          this._hasAniObj = void 0;
          this._texGrids = void 0;
          this.aniObjects = void 0;
          this._objects = [];
        }
        get premultiplyAlpha() {
          return this._premultiplyAlpha;
        }
        set premultiplyAlpha(value) {
          this._premultiplyAlpha = value;
        }
        getPositionOffset() {
          return this._positionOffset;
        }
        getProperties() {
          return this._properties;
        }
        getGroupName() {
          return this._groupName;
        }
        getProperty(propertyName) {
          return this._properties[propertyName.toString()];
        }
        getObject(objectName) {
          for (let i = 0, len = this._objects.length; i < len; i++) {
            const obj = this._objects[i];
            if (obj && obj.name === objectName) {
              return obj;
            }
          }
          return null;
        }
        getObjects() {
          return this._objects;
        }
        get offset() {
          return this._offset;
        }
        _init(groupInfo, mapInfo, texGrids) {
          const FLIPPED_MASK = 268435455;
          const FLAG_HORIZONTAL = 2147483648;
          const FLAG_VERTICAL = 1073741824;
          this._groupName = groupInfo.name;
          this._positionOffset = groupInfo.offset;
          this._mapInfo = mapInfo;
          this._properties = groupInfo.getProperties();
          this._offset = new Vec2(groupInfo.offset.x, -groupInfo.offset.y);
          this._opacity = groupInfo.opacity;
          if (groupInfo.tintColor) {
            this._tintColor = groupInfo.tintColor;
          }
          this._texGrids = texGrids;
          this._animations = mapInfo.getTileAnimations();
          this.aniObjects = [];
          this._hasAniObj = false;
          const mapSize = mapInfo.mapSize;
          const tileSize = mapInfo.tileSize;
          let width = 0;
          let height = 0;
          const colorVal = new Color$1();
          const iso = 2 === mapInfo.orientation;
          if (mapInfo.orientation === 1) {
            if (mapInfo.getStaggerAxis() === 0) {
              height = tileSize.height * (mapSize.height + 0.5);
              width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2);
            } else {
              width = tileSize.width * (mapSize.width + 0.5);
              height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2);
            }
          } else if (iso) {
            const wh = mapSize.width + mapSize.height;
            width = tileSize.width * 0.5 * wh;
            height = tileSize.height * 0.5 * wh;
          } else {
            width = mapSize.width * tileSize.width;
            height = mapSize.height * tileSize.height;
          }
          const transComp = this.node._uiProps.uiTransformComp;
          transComp.setContentSize(width, height);
          const leftTopX = width * transComp.anchorX;
          const leftTopY = height * (1 - transComp.anchorY);
          const objects = groupInfo.objects;
          const aliveNodes = {};
          for (let i = 0, l = objects.length; i < l; i++) {
            const object = objects[i];
            const objType = object.type;
            object.offset = new Vec2(object.x, object.y);
            const points = object.points || object.polylinePoints;
            if (points) {
              for (let pi = 0; pi < points.length; pi++) {
                points[pi].y *= -1;
              }
            }
            if (iso) {
              const posIdxX = object.x / tileSize.height;
              const posIdxY = object.y / tileSize.height;
              object.x = tileSize.width * 0.5 * (mapSize.height + posIdxX - posIdxY);
              object.y = tileSize.height * 0.5 * (mapSize.width + mapSize.height - posIdxX - posIdxY);
            } else {
              object.y = height - object.y;
            }
            if (objType === 5) {
              const textName = `text${object.id}`;
              aliveNodes[textName] = true;
              let textNode = this.node.getChildByName(textName);
              if (!textNode) {
                textNode = new Node$1();
              }
              textNode.setRotationFromEuler(0, 0, -object.rotation);
              textNode.setPosition(object.x - leftTopX, object.y - leftTopY);
              textNode.name = textName;
              textNode.parent = this.node;
              textNode.setSiblingIndex(i);
              textNode.layer = this.node.layer;
              let label = textNode.getComponent(Label);
              if (!label) {
                label = textNode.addComponent(Label);
              }
              const textTransComp = textNode._uiProps.uiTransformComp;
              textNode.active = object.visible;
              textTransComp.anchorX = 0;
              textTransComp.anchorY = 1;
              if (this._tintColor) {
                colorVal.set(this._tintColor);
                colorVal.a *= this._opacity / 255;
                label.color.set(colorVal);
              } else {
                const c = label.color;
                c.a *= this._opacity / 255;
              }
              label.overflow = Label.Overflow.SHRINK;
              label.lineHeight = object.height;
              label.string = object.text;
              label.horizontalAlign = object.halign;
              label.verticalAlign = object.valign;
              label.fontSize = object.pixelsize;
              textTransComp.setContentSize(object.width, object.height);
            } else if (objType === 4) {
              const gid = object.gid;
              const gridGID = (gid & FLIPPED_MASK) >>> 0;
              const grid = texGrids.get(gridGID);
              if (!grid) continue;
              const tileset = grid.tileset;
              const imgName = `img${object.id}`;
              aliveNodes[imgName] = true;
              let imgNode = this.node.getChildByName(imgName);
              object.width = object.width || grid.width;
              object.height = object.height || grid.height;
              if (imgNode && imgNode._objFlags & CCObject.Flags.HideInHierarchy) {
                imgNode.removeFromParent();
                imgNode.hideFlags |= CCObject.Flags.DontSave;
                imgNode.destroy();
                imgNode = null;
              }
              if (!imgNode) {
                imgNode = new Node$1();
              }
              if (this._animations.get(gridGID)) {
                this.aniObjects.push({
                  object,
                  imgNode,
                  gridGID
                });
                this._hasAniObj = true;
              }
              const tileOffsetX = tileset.tileOffset.x;
              const tileOffsetY = tileset.tileOffset.y;
              imgNode.active = object.visible;
              imgNode.setRotationFromEuler(0, 0, -object.rotation);
              imgNode.setPosition(object.x - leftTopX, object.y - leftTopY);
              imgNode.name = imgName;
              imgNode.parent = this.node;
              imgNode.setSiblingIndex(i);
              imgNode.layer = this.node.layer;
              let sprite = imgNode.getComponent(Sprite);
              if (!sprite) {
                sprite = imgNode.addComponent(Sprite);
              }
              const imgTrans = imgNode._uiProps.uiTransformComp;
              if (iso) {
                imgTrans.anchorX = 0.5 + tileOffsetX / object.width;
                imgTrans.anchorY = tileOffsetY / object.height;
              } else {
                imgTrans.anchorX = tileOffsetX / object.width;
                imgTrans.anchorY = tileOffsetY / object.height;
              }
              if (this._tintColor) {
                colorVal.set(this._tintColor);
                colorVal.a *= this._opacity / 255;
                sprite.color.set(colorVal);
              } else {
                const c = sprite.color;
                c.a *= this._opacity / 255;
              }
              sprite.sizeMode = Sprite.SizeMode.CUSTOM;
              const srcBlendFactor = this._premultiplyAlpha ? 1 : 2;
              if (sprite.srcBlendFactor !== srcBlendFactor) {
                sprite.srcBlendFactor = srcBlendFactor;
                if (sprite.material) {
                  sprite._updateBlendFunc();
                }
              }
              let spf = grid.spriteFrame;
              if (!spf) {
                spf = new SpriteFrame();
              } else {
                spf = spf.clone();
              }
              if ((gid & FLAG_HORIZONTAL) >>> 0) {
                spf.flipUVX = !spf.flipUVX;
              }
              if ((gid & FLAG_VERTICAL) >>> 0) {
                spf.flipUVY = !spf.flipUVY;
              }
              spf.rotated = grid._rotated;
              spf.rect = grid._rect;
              sprite.spriteFrame = spf;
              imgTrans.setContentSize(object.width, object.height);
              sprite.markForUpdateRenderData();
            }
          }
          this._objects = objects;
          const children = this.node.children;
          const uselessExp = /^(?:img|text)\d+$/;
          for (let i = 0, n = children.length; i < n; i++) {
            const c = children[i];
            const cName = c.name;
            const isUseless = uselessExp.test(cName);
            if (isUseless && !aliveNodes[cName]) c.destroy();
          }
        }
        update(dt) {
          if (!this._hasAniObj) {
            return;
          }
          const aniObjects = this.aniObjects;
          const _texGrids = this._texGrids;
          const iso = 2 === this._mapInfo.orientation;
          for (let i = 0, len = aniObjects.length; i < len; i++) {
            const aniObj = aniObjects[i];
            const gridGID = aniObj.gridGID;
            const grid = _texGrids.get(gridGID);
            if (!grid) {
              continue;
            }
            const tileset = grid.tileset;
            const object = aniObj.object;
            const imgNode = aniObj.imgNode;
            const tileOffsetX = tileset.tileOffset.x;
            const tileOffsetY = tileset.tileOffset.y;
            const imgTrans = imgNode._uiProps.uiTransformComp;
            if (iso) {
              imgTrans.anchorX = 0.5 + tileOffsetX / object.width;
              imgTrans.anchorY = tileOffsetY / object.height;
            } else {
              imgTrans.anchorX = tileOffsetX / object.width;
              imgTrans.anchorY = tileOffsetY / object.height;
            }
            const sp = imgNode.getComponent(Sprite);
            const spf = sp.spriteFrame;
            spf.rotated = grid._rotated;
            spf.rect = grid._rect;
            sp.spriteFrame = spf;
            sp.markForUpdateRenderData();
          }
        }
      }, (_applyDecoratedDescriptor(_class2$k.prototype, "premultiplyAlpha", [_dec3$j], Object.getOwnPropertyDescriptor(_class2$k.prototype, "premultiplyAlpha"), _class2$k.prototype)), _class2$k)) || _class$n) || _class$n));

      var _dec$m, _dec2$j, _dec3$i, _dec4$d, _dec5$d, _dec6$7, _dec7$5, _dec8$4, _class$m, _class2$j, _initializer$j, _initializer2$h, _initializer3$e, _initializer4$c, _initializer5$a, _initializer6$7, _initializer7$7, _initializer8$7;
      let TiledMapAsset = exports("TiledMapAsset", (_dec$m = ccclass$H('cc.TiledMapAsset'), _dec2$j = type$a([TextAsset]), _dec3$i = type$a([CCString]), _dec4$d = type$a([SpriteFrame]), _dec5$d = type$a([SpriteFrame]), _dec6$7 = type$a([CCString]), _dec7$5 = type$a([CCString]), _dec8$4 = type$a([Size$1]), _dec$m(_class$m = (_class2$j = class TiledMapAsset extends Asset {
        constructor() {
          super();
          this.tmxXmlStr = _initializer$j && _initializer$j();
          this.tsxFiles = _initializer2$h && _initializer2$h();
          this.tsxFileNames = _initializer3$e && _initializer3$e();
          this.spriteFrames = _initializer4$c && _initializer4$c();
          this.imageLayerSpriteFrame = _initializer5$a && _initializer5$a();
          this.imageLayerSpriteFrameNames = _initializer6$7 && _initializer6$7();
          this.spriteFrameNames = _initializer7$7 && _initializer7$7();
          this.spriteFrameSizes = _initializer8$7 && _initializer8$7();
        }
      }, (_initializer$j = applyDecoratedInitializer(_class2$j.prototype, "tmxXmlStr", [serializable$l], function () {
        return '';
      }), _initializer2$h = applyDecoratedInitializer(_class2$j.prototype, "tsxFiles", [serializable$l, _dec2$j], function () {
        return [];
      }), _initializer3$e = applyDecoratedInitializer(_class2$j.prototype, "tsxFileNames", [serializable$l, _dec3$i], function () {
        return [];
      }), _initializer4$c = applyDecoratedInitializer(_class2$j.prototype, "spriteFrames", [serializable$l, _dec4$d], function () {
        return [];
      }), _initializer5$a = applyDecoratedInitializer(_class2$j.prototype, "imageLayerSpriteFrame", [serializable$l, _dec5$d], function () {
        return [];
      }), _initializer6$7 = applyDecoratedInitializer(_class2$j.prototype, "imageLayerSpriteFrameNames", [serializable$l, _dec6$7], function () {
        return [];
      }), _initializer7$7 = applyDecoratedInitializer(_class2$j.prototype, "spriteFrameNames", [serializable$l, _dec7$5], function () {
        return [];
      }), _initializer8$7 = applyDecoratedInitializer(_class2$j.prototype, "spriteFrameSizes", [serializable$l, _dec8$4], function () {
        return [];
      })), _class2$j)) || _class$m));

      var _dec$l, _dec2$i, _dec3$h, _class$l, _class2$i, _initializer$i, _initializer2$g, _initializer3$d, _class3$d;
      let TiledMap = exports("TiledMap", (_dec$l = ccclass$H('cc.TiledMap'), _dec2$i = requireComponent(UITransform), _dec3$h = type$a(TiledMapAsset), _dec$l(_class$l = _dec2$i(_class$l = (_class2$i = (_class3$d = class TiledMap extends Component {
        get tmxAsset() {
          return this._tmxFile;
        }
        set tmxAsset(value) {
          if (this._tmxFile !== value || EDITOR) {
            this._tmxFile = value;
            this._applyFile();
            this._isApplied = true;
          }
        }
        get enableCulling() {
          return this._enableCulling;
        }
        set enableCulling(value) {
          this._enableCulling = value;
          const layers = this._layers;
          for (let i = 0; i < layers.length; ++i) {
            layers[i].enableCulling = value;
          }
        }
        constructor() {
          super();
          this._texGrids = new Map();
          this._textures = [];
          this._tilesets = [];
          this._animations = new Map();
          this._imageLayers = [];
          this._layers = [];
          this._groups = [];
          this._images = [];
          this._properties = {};
          this._tileProperties = new Map();
          this._mapInfo = null;
          this._mapSize = new Size$1(0, 0);
          this._tileSize = new Size$1(0, 0);
          this._mapOrientation = 0;
          this._isApplied = false;
          this._tmxFile = _initializer$i && _initializer$i();
          this._enableCulling = _initializer2$g && _initializer2$g();
          this.cleanupImageCache = _initializer3$d && _initializer3$d();
        }
        getMapSize() {
          return this._mapSize;
        }
        getTileSize() {
          return this._tileSize;
        }
        getMapOrientation() {
          return this._mapOrientation;
        }
        getObjectGroups() {
          return this._groups;
        }
        getObjectGroup(groupName) {
          const groups = this._groups;
          for (let i = 0, l = groups.length; i < l; i++) {
            const group = groups[i];
            if (group && group.getGroupName() === groupName) {
              return group;
            }
          }
          return null;
        }
        getProperties() {
          return this._properties;
        }
        getLayers() {
          return this._layers;
        }
        getLayer(layerName) {
          const layers = this._layers;
          for (let i = 0, l = layers.length; i < l; i++) {
            const layer = layers[i];
            if (layer && layer.getLayerName() === layerName) {
              return layer;
            }
          }
          return null;
        }
        _changeLayer(layerName, replaceLayer) {
          const layers = this._layers;
          for (let i = 0, l = layers.length; i < l; i++) {
            const layer = layers[i];
            if (layer && layer.getLayerName() === layerName) {
              layers[i] = replaceLayer;
              return;
            }
          }
        }
        getProperty(propertyName) {
          return this._properties[propertyName.toString()];
        }
        getPropertiesForGID(gid) {
          return this._tileProperties.get(gid);
        }
        __preload() {
          if (!this._tmxFile) {
            return;
          }
          if (this._isApplied === false) {
            this._applyFile();
            this._isApplied = true;
          }
        }
        onEnable() {
          this.node.on("anchor-changed", this._syncAnchorPoint, this);
        }
        onDisable() {
          this.node.off("anchor-changed", this._syncAnchorPoint, this);
        }
        _applyFile() {
          const spriteFrames = [];
          const spriteFramesCache = {};
          const file = this._tmxFile;
          if (file) {
            let spfNames = file.spriteFrameNames;
            const spfSizes = file.spriteFrameSizes;
            const fSpriteFrames = file.spriteFrames;
            const spfTexturesMap = {};
            const spfTextureSizeMap = {};
            for (let i = 0; i < spfNames.length; ++i) {
              const texName = spfNames[i];
              spfTextureSizeMap[texName] = spfSizes[i];
              spriteFrames[i] = fSpriteFrames[i];
              const frame = spriteFrames[i];
              if (frame) {
                spriteFramesCache[frame.name] = frame;
                spfTexturesMap[texName] = frame;
              }
            }
            const imageLayerTextures = {};
            const texValues = file.imageLayerSpriteFrame;
            spfNames = file.imageLayerSpriteFrameNames;
            for (let i = 0; i < texValues.length; ++i) {
              imageLayerTextures[spfNames[i]] = texValues[i];
            }
            const tsxFileNames = file.tsxFileNames;
            const tsxFiles = file.tsxFiles;
            const tsxContentMap = {};
            for (let i = 0; i < tsxFileNames.length; ++i) {
              if (tsxFileNames[i].length > 0) {
                tsxContentMap[tsxFileNames[i]] = tsxFiles[i].text;
              }
            }
            const mapInfo = new TMXMapInfo(file.tmxXmlStr, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures);
            const tilesets = mapInfo.getTilesets();
            if (!tilesets || tilesets.length === 0) {
              logID(7241);
            }
            this._buildWithMapInfo(mapInfo);
          } else {
            this._releaseMapInfo();
          }
        }
        _releaseMapInfo() {
          const layers = this._layers;
          for (let i = 0, l = layers.length; i < l; i++) {
            var _layers$i$node$parent, _layers$i$node$parent2;
            (_layers$i$node$parent = layers[i].node.parent) === null || _layers$i$node$parent === void 0 ? void 0 : _layers$i$node$parent.off("size-changed", layers[i].updateCulling, layers[i]);
            (_layers$i$node$parent2 = layers[i].node.parent) === null || _layers$i$node$parent2 === void 0 ? void 0 : _layers$i$node$parent2.off("transform-changed", layers[i].updateCulling, layers[i]);
            layers[i].node.removeFromParent();
            layers[i].node.destroy();
          }
          layers.length = 0;
          const groups = this._groups;
          for (let i = 0, l = groups.length; i < l; i++) {
            groups[i].node.removeFromParent();
            groups[i].node.destroy();
          }
          groups.length = 0;
          const images = this._images;
          for (let i = 0, l = images.length; i < l; i++) {
            images[i].removeFromParent();
            images[i].destroy();
          }
          images.length = 0;
        }
        _syncAnchorPoint() {
          const anchor = this.node._uiProps.uiTransformComp.anchorPoint;
          const leftTopX = this.node._uiProps.uiTransformComp.width * anchor.x;
          const leftTopY = this.node._uiProps.uiTransformComp.height * (1 - anchor.y);
          let i;
          let l;
          for (i = 0, l = this._layers.length; i < l; i++) {
            const layerInfo = this._layers[i];
            const layerNode = layerInfo.node;
            layerNode._uiProps.uiTransformComp.setAnchorPoint(anchor);
          }
          for (i = 0, l = this._groups.length; i < l; i++) {
            const groupInfo = this._groups[i];
            const groupNode = groupInfo.node._uiProps.uiTransformComp;
            groupNode.anchorX = 0.5;
            groupNode.anchorY = 0.5;
            const x = groupInfo.offset.x - leftTopX + groupNode.width * groupNode.anchorX;
            const y = groupInfo.offset.y + leftTopY - groupNode.height * groupNode.anchorY;
            groupInfo.node.setPosition(x, y);
          }
          for (i = 0, l = this._images.length; i < l; i++) {
            const image = this._images[i]._uiProps.uiTransformComp;
            image.anchorX = 0.5;
            image.anchorY = 0.5;
            const x = this._images[i]._offset.x - leftTopX + image.width * image.anchorX;
            const y = this._images[i]._offset.y + leftTopY - image.height * image.anchorY;
            this._images[i].setPosition(x, y);
          }
        }
        _fillAniGrids(texGrids, animations) {
          for (const i of animations.keys()) {
            const animation = animations.get(i);
            if (!animation) continue;
            const frames = animation.frames;
            for (let j = 0; j < frames.length; j++) {
              const frame = frames[j];
              frame.grid = texGrids.get(frame.tileid);
            }
          }
        }
        _buildLayerAndGroup() {
          const tilesets = this._tilesets;
          const texGrids = this._texGrids;
          const animations = this._animations;
          texGrids.clear();
          for (let i = 0, l = tilesets.length; i < l; ++i) {
            const tilesetInfo = tilesets[i];
            if (!tilesetInfo) continue;
            if (!tilesetInfo.sourceImage) {
              warnID(16406, i);
              continue;
            }
            fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
          }
          this._fillAniGrids(texGrids, animations);
          let layers = this._layers;
          let groups = this._groups;
          let images = this._images;
          const oldNodeNames = {};
          for (let i = 0, n = layers.length; i < n; i++) {
            oldNodeNames[layers[i].node.name] = true;
          }
          for (let i = 0, n = groups.length; i < n; i++) {
            oldNodeNames[groups[i].node.name] = true;
          }
          for (let i = 0, n = images.length; i < n; i++) {
            oldNodeNames[images[i].name] = true;
          }
          layers = this._layers = [];
          groups = this._groups = [];
          images = this._images = [];
          const mapInfo = this._mapInfo;
          const node = this.node;
          const layerInfos = mapInfo.getAllChildren();
          const textures = this._textures;
          let maxWidth = 0;
          let maxHeight = 0;
          if (layerInfos && layerInfos.length > 0) {
            for (let i = 0, len = layerInfos.length; i < len; i++) {
              const layerInfo = layerInfos[i];
              const name = layerInfo.name;
              let child = this.node.getChildByName(name);
              oldNodeNames[name] = false;
              if (!child) {
                child = new Node$1();
                child.name = name;
                child.layer = node.layer;
                node.addChild(child);
              }
              child.setSiblingIndex(i);
              child.active = layerInfo.visible;
              if (layerInfo instanceof TMXLayerInfo) {
                let layer = child.getComponent(TiledLayer);
                if (!layer) {
                  layer = child.addComponent(TiledLayer);
                }
                layer.init(layerInfo, mapInfo, tilesets, textures, texGrids);
                layer.enableCulling = this._enableCulling;
                layerInfo.ownTiles = false;
                layers.push(layer);
              } else if (layerInfo instanceof TMXObjectGroupInfo) {
                let group = child.getComponent(TiledObjectGroup);
                if (!group) {
                  group = child.addComponent(TiledObjectGroup);
                }
                group._init(layerInfo, mapInfo, texGrids);
                groups.push(group);
              } else if (layerInfo instanceof TMXImageLayerInfo) {
                const spriteFrame = layerInfo.sourceImage;
                child.layerInfo = layerInfo;
                child._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
                let image = child.getComponent(Sprite);
                if (!image) {
                  image = child.addComponent(Sprite);
                }
                const color = image.color;
                color.a *= layerInfo.opacity;
                image.spriteFrame = spriteFrame;
                let width = spriteFrame.width;
                let height = spriteFrame.height;
                if (spriteFrame.original) {
                  width = spriteFrame.originalSize.width;
                  height = spriteFrame.originalSize.height;
                }
                child._uiProps.uiTransformComp.setContentSize(width, height);
                images.push(child);
              }
              maxWidth = Math.max(maxWidth, child._uiProps.uiTransformComp.width);
              maxHeight = Math.max(maxHeight, child._uiProps.uiTransformComp.height);
            }
          }
          const children = node.children;
          for (let i = 0, n = children.length; i < n; i++) {
            const c = children[i];
            if (oldNodeNames[c.name]) {
              c.destroy();
            }
          }
          this.node._uiProps.uiTransformComp.setContentSize(maxWidth, maxHeight);
          this._syncAnchorPoint();
        }
        _buildWithMapInfo(mapInfo) {
          this._mapInfo = mapInfo;
          this._mapSize = mapInfo.getMapSize();
          this._tileSize = mapInfo.getTileSize();
          this._mapOrientation = mapInfo.orientation;
          this._properties = mapInfo.properties;
          this._tileProperties = mapInfo.getTileProperties();
          this._imageLayers = mapInfo.getImageLayers();
          this._animations = mapInfo.getTileAnimations();
          this._tilesets = mapInfo.getTilesets();
          const tilesets = this._tilesets;
          this._textures.length = 0;
          const totalTextures = [];
          for (let i = 0, l = tilesets.length; i < l; ++i) {
            const tilesetInfo = tilesets[i];
            if (!tilesetInfo || !tilesetInfo.sourceImage) continue;
            this._textures[i] = tilesetInfo.sourceImage;
            totalTextures.push(tilesetInfo.sourceImage);
          }
          for (let i = 0; i < this._imageLayers.length; i++) {
            const imageLayer = this._imageLayers[i];
            if (!imageLayer || !imageLayer.sourceImage) continue;
            totalTextures.push(imageLayer.sourceImage);
          }
          this._buildLayerAndGroup();
          if (this.cleanupImageCache) {
            this._textures.forEach(tex => {
              this.doCleanupImageCache(tex);
            });
          }
        }
        doCleanupImageCache(texture) {
          if (texture._image instanceof HTMLImageElement) {
            texture._image.src = '';
            texture._image.destroy();
          } else if (sys.hasFeature(sys.Feature.IMAGE_BITMAP) && texture._image instanceof ImageBitmap) {
            if (texture._image.close) texture._image.close();
          }
          texture._image = null;
        }
        lateUpdate(dt) {
          const animations = this._animations;
          const texGrids = this._texGrids;
          for (const aniGID of animations.keys()) {
            const animation = animations.get(aniGID);
            const frames = animation.frames;
            let frame = frames[animation.frameIdx];
            animation.dt += dt;
            if (frame.duration < animation.dt) {
              animation.dt = 0;
              animation.frameIdx++;
              if (animation.frameIdx >= frames.length) {
                animation.frameIdx = 0;
              }
              frame = frames[animation.frameIdx];
            }
            texGrids.set(aniGID, frame.grid);
          }
          const layers = this.getLayers();
          for (let i = 0, l = layers.length; i < l; i++) {
            const layer = layers[i];
            if (layer.hasAnimation() || layer.node.hasChangedFlags) {
              layer.markForUpdateRenderData();
            }
          }
        }
      }, _class3$d.Orientation = Orientation, _class3$d.Property = Property, _class3$d.TileFlag = TileFlag, _class3$d.StaggerAxis = StaggerAxis, _class3$d.StaggerIndex = StaggerIndex, _class3$d.TMXObjectType = TMXObjectType, _class3$d.RenderOrder = RenderOrder, _class3$d), (_initializer$i = applyDecoratedInitializer(_class2$i.prototype, "_tmxFile", [serializable$l], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$i.prototype, "tmxAsset", [_dec3$h], Object.getOwnPropertyDescriptor(_class2$i.prototype, "tmxAsset"), _class2$i.prototype), _initializer2$g = applyDecoratedInitializer(_class2$i.prototype, "_enableCulling", [serializable$l], function () {
        return true;
      }), _initializer3$d = applyDecoratedInitializer(_class2$i.prototype, "cleanupImageCache", [serializable$l], function () {
        return true;
      })), _class2$i)) || _class$l) || _class$l));

      const MaxGridsLimit = Math.ceil(65535 / 6);
      const vec3_temps = [];
      for (let i = 0; i < 4; i++) {
        vec3_temps.push(new Vec3());
      }
      const _mat4_temp$2 = new Mat4();
      const _vec3u_temp = new Vec3();
      const _leftDown = {
        row: 0,
        col: 0
      };
      let _uva = {
        x: 0,
        y: 0
      };
      let _uvb = {
        x: 0,
        y: 0
      };
      let _uvc = {
        x: 0,
        y: 0
      };
      let _uvd = {
        x: 0,
        y: 0
      };
      let _vfOffset = 0;
      let _moveX = 0;
      let _moveY = 0;
      let _fillCount = 0;
      let _curTexture = null;
      let _tempBuffers;
      let _curLayer;
      let flipTexture;
      let _accessor = null;
      const simple = {
        ensureAccessor() {
          if (!_accessor) {
            const device = director.root.device;
            director.root.batcher2D;
            _accessor = new StaticVBAccessor(device, vfmtPosUvColor, this.vCount);
            director.on("director_before_draw", () => {
              _accessor.reset();
            });
          }
        },
        createData(layer) {
          {
            this.ensureAccessor();
          }
        },
        fillBuffers(layer, renderer) {
          if (!layer || layer.tiledDataArray.length === 0) return;
          const dataArray = layer.tiledDataArray;
          const data = dataArray[layer._tiledDataArrayIdx];
          const renderData = data.renderData;
          const iBuf = renderData.chunk.meshBuffer.iData;
          let indexOffset = renderData.chunk.meshBuffer.indexOffset;
          let vertexId = renderData.chunk.vertexOffset;
          const quadCount = renderData.vertexCount / 4;
          for (let i = 0; i < quadCount; i += 1) {
            iBuf[indexOffset] = vertexId;
            iBuf[indexOffset + 1] = vertexId + 1;
            iBuf[indexOffset + 2] = vertexId + 2;
            iBuf[indexOffset + 3] = vertexId + 2;
            iBuf[indexOffset + 4] = vertexId + 1;
            iBuf[indexOffset + 5] = vertexId + 3;
            indexOffset += 6;
            vertexId += 4;
          }
          renderData.chunk.meshBuffer.indexOffset = indexOffset;
        },
        updateRenderData(comp) {
          comp.updateCulling();
          _moveX = comp.leftDownToCenterX;
          _moveY = comp.leftDownToCenterY;
          if (comp.colorChanged || comp.isCullingDirty() || comp.isUserNodeDirty() || comp.hasAnimation() || comp.hasTiledNode() || comp.node.hasChangedFlags) {
            comp.colorChanged = false;
            comp.destroyRenderData();
            let leftDown;
            let rightTop;
            if (comp.enableCulling) {
              const cullingRect = comp.cullingRect;
              leftDown = cullingRect.leftDown;
              rightTop = cullingRect.rightTop;
            } else {
              leftDown = _leftDown;
              rightTop = comp.rightTop;
            }
            switch (comp.renderOrder) {
              case 0:
                traverseGrids(leftDown, rightTop, -1, 1, comp);
                break;
              case 2:
                traverseGrids(leftDown, rightTop, -1, -1, comp);
                break;
              case 1:
                traverseGrids(leftDown, rightTop, 1, 1, comp);
                break;
              case 3:
              default:
                traverseGrids(leftDown, rightTop, 1, -1, comp);
                break;
            }
            comp.setCullingDirty(false);
            comp.setUserNodeDirty(false);
          }
          {
            comp.prepareDrawData();
          }
        },
        updateColor(tiled) {
          const color = tiled.color;
          const colorV = new Float32Array(4);
          colorV[0] = color.r / 255;
          colorV[1] = color.g / 255;
          colorV[2] = color.b / 255;
          colorV[3] = color.a / 255;
          const rs = tiled.tiledDataArray;
          for (const r of rs) {
            if (!r.renderData) continue;
            const renderData = r.renderData;
            const vs = renderData.vData;
            for (let i = renderData.vertexStart, l = renderData.vertexCount; i < l; i++) {
              vs.set(colorV, i * 9 + 5);
            }
          }
        }
      };
      function _flipTexture(inGrid, gid) {
        if (inGrid._rotated) {
          _uva.x = inGrid.r;
          _uva.y = inGrid.t;
          _uvb.x = inGrid.l;
          _uvb.y = inGrid.t;
          _uvc.x = inGrid.r;
          _uvc.y = inGrid.b;
          _uvd.x = inGrid.l;
          _uvd.y = inGrid.b;
        } else {
          _uva.x = inGrid.l;
          _uva.y = inGrid.t;
          _uvb.x = inGrid.l;
          _uvb.y = inGrid.b;
          _uvc.x = inGrid.r;
          _uvc.y = inGrid.t;
          _uvd.x = inGrid.r;
          _uvd.y = inGrid.b;
        }
        let tempVal;
        if ((gid & 536870912) >>> 0) {
          tempVal = _uvb;
          _uvb = _uvc;
          _uvc = tempVal;
        }
        if ((gid & 2147483648) >>> 0) {
          tempVal = _uva;
          _uva = _uvc;
          _uvc = tempVal;
          tempVal = _uvb;
          _uvb = _uvd;
          _uvd = tempVal;
        }
        if ((gid & 1073741824) >>> 0) {
          tempVal = _uva;
          _uva = _uvb;
          _uvb = tempVal;
          tempVal = _uvc;
          _uvc = _uvd;
          _uvd = tempVal;
        }
      }
      function packRenderData() {
        if (_fillCount < 1 || !_curTexture) return;
        const vbCount = 4 * _fillCount;
        const ibCount = 6 * _fillCount;
        const tiledData = _curLayer.requestTiledRenderData();
        {
          tiledData.renderData = RenderData.add(vfmtPosUvColor, _accessor);
          tiledData.renderData.drawInfoType = 2;
        }
        tiledData.texture = _curTexture;
        const rd = tiledData.renderData;
        rd.resize(vbCount, ibCount);
        const vb = rd.chunk.vb;
        vb.set(_tempBuffers.subarray(0, vbCount * 9), 0);
        _fillCount = 0;
        _curTexture = null;
      }
      function traverseGrids(leftDown, rightTop, rowMoveDir, colMoveDir, comp) {
        if (rightTop.row < 0 || rightTop.col < 0) return;
        _curLayer = comp;
        const matrix = comp.node.worldMatrix;
        _vfOffset = 0;
        const tiledTiles = comp.tiledTiles;
        const texGrids = comp.texGrids;
        const tiles = comp.tiles;
        const vertStep = 9;
        const vertStep2 = vertStep * 2;
        const vertStep3 = vertStep * 3;
        const vertices = comp.vertices;
        let rowData;
        let col;
        let cols;
        let row;
        let rows;
        let colData;
        let tileSize;
        let grid;
        let gid = 0;
        let left = 0;
        let bottom = 0;
        let right = 0;
        let top = 0;
        let tiledNode;
        let colNodesCount = 0;
        let isCheckColRange = true;
        flipTexture = _flipTexture;
        const color = new Float32Array(4);
        color[0] = comp.color.r / 255;
        color[1] = comp.color.g / 255;
        color[2] = comp.color.b / 255;
        color[3] = comp.color.a / 255;
        if (rowMoveDir === -1) {
          row = rightTop.row;
          rows = leftDown.row;
        } else {
          row = leftDown.row;
          rows = rightTop.row;
        }
        const _tempRows = Math.abs(leftDown.row - rightTop.row) + 1;
        const _tempClos = Math.abs(rightTop.col - leftDown.col) + 1;
        _tempBuffers = new Float32Array(_tempRows * _tempClos * 9 * 4);
        _fillCount = 0;
        const vertexBuf = _tempBuffers;
        for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) {
          rowData = vertices[row];
          colNodesCount = comp.getNodesCountByRow(row);
          isCheckColRange = rowData && colNodesCount === 0;
          if (colMoveDir === 1) {
            col = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
            cols = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
          } else {
            col = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
            cols = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
          }
          for (; (cols - col) * colMoveDir >= 0; col += colMoveDir) {
            colData = rowData && rowData[col];
            if (colNodesCount > 0) {
              packRenderData();
              const nodes = comp.requestSubNodesData();
              const celData = comp.getNodesByRowCol(row, col);
              if (celData && celData.count > 0) {
                nodes.subNodes = celData.list;
              }
            }
            if (!colData) {
              continue;
            }
            gid = tiles[colData.index];
            grid = texGrids.get((gid & 268435455) >>> 0);
            if (!grid) continue;
            if (_curTexture !== grid.texture) {
              packRenderData();
              _curTexture = grid.texture;
            }
            tileSize = grid.tileset._tileSize;
            left = colData.left - _moveX;
            bottom = colData.bottom - _moveY;
            right = left + tileSize.width;
            top = bottom + tileSize.height;
            tiledNode = tiledTiles[colData.index];
            _vfOffset = _fillCount * 4 * 9;
            if (!tiledNode) {
              {
                vec3_temps[0].x = left;
                vec3_temps[0].y = top;
                vec3_temps[1].x = left;
                vec3_temps[1].y = bottom;
                vec3_temps[2].x = right;
                vec3_temps[2].y = top;
                vec3_temps[3].x = right;
                vec3_temps[3].y = bottom;
              }
              vec3_temps[0].transformMat4(matrix);
              vertexBuf[_vfOffset] = vec3_temps[0].x;
              vertexBuf[_vfOffset + 1] = vec3_temps[0].y;
              vertexBuf[_vfOffset + 2] = vec3_temps[0].z;
              vec3_temps[1].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep] = vec3_temps[1].x;
              vertexBuf[_vfOffset + vertStep + 1] = vec3_temps[1].y;
              vertexBuf[_vfOffset + vertStep + 2] = vec3_temps[1].z;
              vec3_temps[2].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep2] = vec3_temps[2].x;
              vertexBuf[_vfOffset + vertStep2 + 1] = vec3_temps[2].y;
              vertexBuf[_vfOffset + vertStep2 + 2] = vec3_temps[2].z;
              vec3_temps[3].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep3] = vec3_temps[3].x;
              vertexBuf[_vfOffset + vertStep3 + 1] = vec3_temps[3].y;
              vertexBuf[_vfOffset + vertStep3 + 2] = vec3_temps[3].z;
              vertexBuf.set(color, _vfOffset + 5);
              vertexBuf.set(color, _vfOffset + vertStep + 5);
              vertexBuf.set(color, _vfOffset + vertStep2 + 5);
              vertexBuf.set(color, _vfOffset + vertStep3 + 5);
            } else if (tiledNode.node.active) {
              fillByTiledNode(tiledNode.node, color, vertexBuf, left, right, top, bottom);
            }
            flipTexture(grid, gid);
            vertexBuf[_vfOffset + 3] = _uva.x;
            vertexBuf[_vfOffset + 4] = _uva.y;
            vertexBuf[_vfOffset + vertStep + 3] = _uvb.x;
            vertexBuf[_vfOffset + vertStep + 4] = _uvb.y;
            vertexBuf[_vfOffset + vertStep2 + 3] = _uvc.x;
            vertexBuf[_vfOffset + vertStep2 + 4] = _uvc.y;
            vertexBuf[_vfOffset + vertStep3 + 3] = _uvd.x;
            vertexBuf[_vfOffset + vertStep3 + 4] = _uvd.y;
            _fillCount++;
            if (_fillCount >= MaxGridsLimit) {
              packRenderData();
            }
          }
        }
        packRenderData();
      }
      function fillByTiledNode(tiledNode, color, vbuf, left, right, top, bottom, diamondTile) {
        const vertStep = 9;
        const vertStep2 = vertStep * 2;
        const vertStep3 = vertStep * 3;
        tiledNode.updateWorldTransform();
        Mat4.fromRTS(_mat4_temp$2, tiledNode.rotation, tiledNode.position, tiledNode.scale);
        Vec3.set(_vec3u_temp, -(left + _moveX), -(bottom + _moveY), 0);
        Mat4.transform(_mat4_temp$2, _mat4_temp$2, _vec3u_temp);
        Mat4.multiply(_mat4_temp$2, tiledNode.parent.worldMatrix, _mat4_temp$2);
        const m = _mat4_temp$2;
        const tx = m.m12;
        const ty = m.m13;
        const a = m.m00;
        const b = m.m01;
        const c = m.m04;
        const d = m.m05;
        const justTranslate = a === 1 && b === 0 && c === 0 && d === 1;
        if (justTranslate) {
          vbuf[_vfOffset] = left + tx;
          vbuf[_vfOffset + 1] = top + ty;
          vbuf[_vfOffset + vertStep] = left + tx;
          vbuf[_vfOffset + vertStep + 1] = bottom + ty;
          vbuf[_vfOffset + vertStep2] = right + tx;
          vbuf[_vfOffset + vertStep2 + 1] = top + ty;
          vbuf[_vfOffset + vertStep3] = right + tx;
          vbuf[_vfOffset + vertStep3 + 1] = bottom + ty;
        } else {
          vbuf[_vfOffset] = left * a + top * c + tx;
          vbuf[_vfOffset + 1] = left * b + top * d + ty;
          vbuf[_vfOffset + vertStep] = left * a + bottom * c + tx;
          vbuf[_vfOffset + vertStep + 1] = left * b + bottom * d + ty;
          vbuf[_vfOffset + vertStep2] = right * a + top * c + tx;
          vbuf[_vfOffset + vertStep2 + 1] = right * b + top * d + ty;
          vbuf[_vfOffset + vertStep3] = right * a + bottom * c + tx;
          vbuf[_vfOffset + vertStep3 + 1] = right * b + bottom * d + ty;
        }
        vbuf.set(color, _vfOffset + 5);
        vbuf.set(color, _vfOffset + vertStep + 5);
        vbuf.set(color, _vfOffset + vertStep2 + 5);
        vbuf.set(color, _vfOffset + vertStep3 + 5);
      }

      const tiledLayerAssembler = exports("tiledLayerAssembler", {
        getAssembler() {
          return simple;
        }
      });
      TiledLayer.Assembler = tiledLayerAssembler;

      const _v3_tmp_1 = new Vec3();
      const _v3_tmp_2 = new Vec3();
      function createSplineProperty(mode, knots) {
        let spline = null;
        return {
          value: knots.length > 0 ? knots[knots.length - 1] : Vec3.ZERO,
          progress(start, end, current, ratio) {
            return spline.getPoint(ratio);
          },
          clone(v) {
            return Vec3.clone(v);
          },
          add(a, b) {
            return a.clone().add(b);
          },
          sub(a, b) {
            return a.clone().subtract(b);
          },
          onStart(param) {
            const {
              start,
              end,
              relative,
              reversed
            } = param;
            spline = Spline.create(mode);
            spline.addKnot(start);
            let reversedLast = null;
            if (relative && reversed) {
              reversedLast = _v3_tmp_2;
              Vec3.subtract(reversedLast, start, knots[knots.length - 1]);
            }
            for (let i = 0, len = knots.length; i < len; ++i) {
              const v = reversed ? knots[len - 1 - i] : knots[i];
              if (relative) {
                if (reversed) {
                  if (i > 0) {
                    spline.addKnot(Vec3.copy(_v3_tmp_1, reversedLast).add(v));
                  }
                } else {
                  spline.addKnot(Vec3.copy(_v3_tmp_1, start).add(v));
                }
              } else {
                spline.addKnot(v);
              }
            }
            if (relative && reversed) {
              spline.addKnot(end);
            }
          },
          onComplete() {
            spline = null;
          },
          onStop() {
            spline = null;
          },
          legacyProgress: false
        };
      }
      function bezier(...knots) {
        return createSplineProperty(1, knots);
      }
      function catmullRom(...knots) {
        return createSplineProperty(2, knots);
      }

      var tweenProgress = /*#__PURE__*/Object.freeze({
        __proto__: null,
        bezier: bezier,
        catmullRom: catmullRom
      });
      exports("tweenProgress", tweenProgress);

      class HashElement {
        constructor() {
          this.actions = [];
          this.target = null;
          this.actionIndex = 0;
          this.currentAction = null;
          this.paused = false;
          this.lock = false;
        }
      }
      class ActionManager {
        constructor() {
          this._hashTargets = new Map();
          this._arrayTargets = [];
          this._currentTarget = void 0;
          this._elementPool = [];
        }
        _getElement(target, paused) {
          let element = this._elementPool.pop();
          if (!element) {
            element = new HashElement();
          }
          element.target = target;
          element.paused = !!paused;
          return element;
        }
        _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);
        }
        _onNodeActiveChanged(target, active) {
          if (active) {
            this.resumeTarget(target);
          } else {
            this.pauseTarget(target);
          }
        }
        _onNodeDestroy(target) {
          this._removeAllActionsFromTarget(target, false);
        }
        _registerNodeEvent(target) {
          if (target.isValid) {
            target.on("active-changed", this._onNodeActiveChanged, this);
            target.on("node-destroyed", this._onNodeDestroy, this);
          }
        }
        _unregisterNodeEvent(target) {
          if (target.isValid) {
            target.off("active-changed", this._onNodeActiveChanged, this);
            target.off("node-destroyed", this._onNodeDestroy, this);
          }
        }
        addAction(action, target, paused) {
          if (!action || !target) {
            errorID(1000);
            return;
          }
          let 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 = [];
          }
          if (element.actions.length === 0 && target instanceof Node$1) {
            this._registerNodeEvent(target);
          }
          element.target = target;
          element.actions.push(action);
          action.startWithTarget(target);
        }
        removeAllActions() {
          const locTargets = this._arrayTargets;
          for (let i = 0; i < locTargets.length; i++) {
            const element = locTargets[i];
            if (element) {
              if (element.target instanceof Node$1) {
                this._unregisterNodeEvent(element.target);
              }
              this._putElement(element);
            }
          }
          this._arrayTargets.length = 0;
          this._hashTargets = new Map();
        }
        removeAllActionsFromTarget(target) {
          this._removeAllActionsFromTarget(target, true);
        }
        _removeAllActionsFromTarget(target, offNodeEvent) {
          if (target == null) return;
          const element = this._hashTargets.get(target);
          if (element) {
            if (offNodeEvent && target instanceof Node$1) {
              this._unregisterNodeEvent(target);
            }
            element.actions.length = 0;
            this._deleteHashElement(element);
          }
        }
        removeAction(action) {
          if (action == null) return;
          const target = action.getOriginalTarget();
          const element = this._hashTargets.get(target);
          if (element) {
            for (let i = 0; i < element.actions.length; i++) {
              if (element.actions[i] === action) {
                element.actions.splice(i, 1);
                if (element.actionIndex >= i) element.actionIndex--;
                break;
              }
            }
          }
        }
        _removeActionByTag(tag, element, target) {
          for (let i = 0, l = element.actions.length; i < l; ++i) {
            const action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
              break;
            }
          }
        }
        _removeAllActionsByTag(tag, element, target) {
          for (let i = element.actions.length - 1; i >= 0; --i) {
            const action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
            }
          }
        }
        removeActionByTag(tag, target) {
          if (tag === -1) logID(1002);
          const hashTargets = this._hashTargets;
          if (target) {
            const element = hashTargets.get(target);
            if (element) {
              this._removeActionByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(element => {
              this._removeActionByTag(tag, element);
            });
          }
        }
        removeAllActionsByTag(tag, target) {
          if (tag === -1) logID(1002);
          const hashTargets = this._hashTargets;
          if (target) {
            const element = hashTargets.get(target);
            if (element) {
              this._removeAllActionsByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(element => {
              this._removeAllActionsByTag(tag, element);
            });
          }
        }
        getActionByTag(tag, target) {
          if (tag === -1) logID(1004);
          const element = this._hashTargets.get(target);
          if (element) {
            if (element.actions != null) {
              for (let i = 0; i < element.actions.length; ++i) {
                const action = element.actions[i];
                if (action && action.getTag() === tag) {
                  return action;
                }
              }
            }
            logID(1005, tag);
          }
          return null;
        }
        getNumberOfRunningActionsInTarget(target) {
          const element = this._hashTargets.get(target);
          if (element) {
            return element.actions ? element.actions.length : 0;
          }
          return 0;
        }
        pauseTarget(target) {
          const element = this._hashTargets.get(target);
          if (element) element.paused = true;
        }
        resumeTarget(target) {
          const element = this._hashTargets.get(target);
          if (element) element.paused = false;
        }
        pauseAllRunningActions() {
          const idsWithActions = [];
          const locTargets = this._arrayTargets;
          for (let i = 0; i < locTargets.length; i++) {
            const element = locTargets[i];
            if (element && !element.paused) {
              element.paused = true;
              if (element.target) {
                idsWithActions.push(element.target);
              }
            }
          }
          return idsWithActions;
        }
        resumeTargets(targetsToResume) {
          if (!targetsToResume) return;
          for (let i = 0; i < targetsToResume.length; i++) {
            if (targetsToResume[i]) this.resumeTarget(targetsToResume[i]);
          }
        }
        pauseTargets(targetsToPause) {
          if (!targetsToPause) return;
          for (let i = 0; i < targetsToPause.length; i++) {
            if (targetsToPause[i]) this.pauseTarget(targetsToPause[i]);
          }
        }
        isActionRunning(action) {
          const elements = this._hashTargets.get(action.getOriginalTarget());
          let index = -1;
          if (elements) index = elements.actions.indexOf(action);
          return index !== -1;
        }
        _removeActionAtIndex(index, element) {
          element.actions.splice(index, 1);
          if (element.actionIndex >= index) element.actionIndex--;
          if (element.actions.length === 0) {
            if (element.target instanceof Node$1) {
              this._unregisterNodeEvent(element.target);
            }
            this._deleteHashElement(element);
          }
        }
        _deleteHashElement(element) {
          let ret = false;
          if (element && !element.lock) {
            if (this._hashTargets.get(element.target)) {
              this._hashTargets.delete(element.target);
              const targets = this._arrayTargets;
              for (let i = 0, l = targets.length; i < l; i++) {
                if (targets[i] === element) {
                  targets.splice(i, 1);
                  break;
                }
              }
              this._putElement(element);
              ret = true;
            }
          }
          return ret;
        }
        update(dt) {
          const locTargets = this._arrayTargets;
          let locCurrTarget;
          for (let elt = 0; elt < locTargets.length; elt++) {
            this._currentTarget = locTargets[elt];
            locCurrTarget = this._currentTarget;
            const 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);
                if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
                  locCurrTarget.currentAction.stop();
                  const action = locCurrTarget.currentAction;
                  locCurrTarget.currentAction = null;
                  this.removeAction(action);
                }
                locCurrTarget.currentAction = null;
              }
              locCurrTarget.lock = false;
            }
            if (locCurrTarget.actions.length === 0) {
              if (target instanceof Node$1) {
                this._unregisterNodeEvent(target);
              }
              if (this._deleteHashElement(locCurrTarget)) {
                elt--;
              }
            }
          }
        }
      }

      class TweenSystem extends System {
        get ActionManager() {
          return this.actionMgr;
        }
        constructor() {
          super();
          this.actionMgr = new ActionManager();
        }
        update(dt) {
          {
            this.actionMgr.update(dt);
          }
        }
      } exports("TweenSystem", TweenSystem);
      TweenSystem.ID = 'TWEEN';
      TweenSystem.instance = void 0;
      director.on("director_init", () => {
        const sys = new TweenSystem();
        TweenSystem.instance = sys;
        director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
      });

      class Action {
        constructor() {
          this.originalTarget = null;
          this.target = null;
          this._owner = null;
          this.tag = -1;
          this._id = undefined;
          this._paused = false;
        }
        isDone() {
          return true;
        }
        startWithTarget(target) {
          this.originalTarget = target;
          this.target = target;
        }
        stop() {
          this.target = null;
        }
        getTarget() {
          return this.target;
        }
        setTarget(target) {
          this.target = target;
        }
        getOriginalTarget() {
          return this.originalTarget;
        }
        setOriginalTarget(originalTarget) {
          this.originalTarget = originalTarget;
        }
        _getWorkerTarget() {
          var _this$_owner;
          const workerTarget = (_this$_owner = this._owner) === null || _this$_owner === void 0 ? void 0 : _this$_owner.getTarget();
          return workerTarget !== null && workerTarget !== void 0 ? workerTarget : this.target;
        }
        getTag() {
          return this.tag;
        }
        setTag(tag) {
          this.tag = tag;
        }
        setId(id) {
          this._id = id;
        }
        getId() {
          return this._id;
        }
        setPaused(paused) {
          this._paused = paused;
        }
      }
      class FiniteTimeAction extends Action {
        constructor() {
          super();
          this._duration = 0;
        }
        getDurationScaled() {
          return this._duration;
        }
        getDuration() {
          return this._duration;
        }
        setDuration(duration) {
          this._duration = duration;
        }
      }

      class ActionInstant extends FiniteTimeAction {
        isDone() {
          return true;
        }
        step(_dt) {
          this.update(1);
        }
        update(_dt) {}
        reverse() {
          return this.clone();
        }
        isUnknownDuration() {
          return false;
        }
      }
      class Show extends ActionInstant {
        update(_dt) {
          const target = this._getWorkerTarget();
          if (!target) return;
          const _renderComps = target.getComponentsInChildren(Renderer);
          for (let i = 0; i < _renderComps.length; ++i) {
            const render = _renderComps[i];
            render.enabled = true;
          }
        }
        reverse() {
          return new Hide();
        }
        clone() {
          const action = new Show();
          action._id = this._id;
          return action;
        }
      }
      function show() {
        return new Show();
      }
      class Hide extends ActionInstant {
        update(_dt) {
          const target = this._getWorkerTarget();
          if (!target) return;
          const _renderComps = target.getComponentsInChildren(Renderer);
          for (let i = 0; i < _renderComps.length; ++i) {
            const render = _renderComps[i];
            render.enabled = false;
          }
        }
        reverse() {
          return new Show();
        }
        clone() {
          const action = new Hide();
          action._id = this._id;
          return action;
        }
      }
      function hide() {
        return new Hide();
      }
      class RemoveSelf extends ActionInstant {
        constructor(isNeedCleanUp) {
          super();
          this._isNeedCleanUp = true;
          if (isNeedCleanUp !== undefined) this.init(isNeedCleanUp);
        }
        update(_dt) {
          const target = this._getWorkerTarget();
          if (!target) return;
          target.removeFromParent();
          if (this._isNeedCleanUp) {
            target.destroy();
          }
        }
        init(isNeedCleanUp) {
          this._isNeedCleanUp = isNeedCleanUp;
          return true;
        }
        reverse() {
          return new RemoveSelf(this._isNeedCleanUp);
        }
        clone() {
          const action = new RemoveSelf(this._isNeedCleanUp);
          action._id = this._id;
          return action;
        }
      }
      function removeSelf(isNeedCleanUp) {
        return new RemoveSelf(isNeedCleanUp);
      }
      class CallFunc extends ActionInstant {
        constructor(selector, callbackThis, data) {
          super();
          this._callbackThis = undefined;
          this._callback = undefined;
          this._data = undefined;
          this.initWithFunction(selector, callbackThis, data);
        }
        initWithFunction(callback, callbackThis, data) {
          if (callback) {
            this._callback = callback;
          }
          if (callbackThis) {
            this._callbackThis = callbackThis;
          }
          if (data !== undefined) {
            this._data = data;
          }
          return true;
        }
        execute() {
          if (this._callback) {
            const target = this._getWorkerTarget();
            this._callback.call(this._callbackThis, target, this._data);
          }
        }
        update(_dt) {
          this.execute();
        }
        getTargetCallback() {
          return this._callbackThis;
        }
        setTargetCallback(sel) {
          if (sel !== this._callbackThis) {
            this._callbackThis = sel;
          }
        }
        clone() {
          const action = new CallFunc();
          action._id = this._id;
          if (this._callback) action.initWithFunction(this._callback, this._callbackThis, this._data);
          return action;
        }
      }
      function callFunc(selector, selectorTarget, data) {
        return new CallFunc(selector, selectorTarget, data);
      }

      class DummyAction extends FiniteTimeAction {
        clone() {
          return new DummyAction();
        }
        reverse() {
          return this.clone();
        }
        update(time) {}
        step(dt) {}
        isUnknownDuration() {
          return false;
        }
      }
      class ActionInterval extends FiniteTimeAction {
        constructor(d) {
          super();
          this.MAX_VALUE = 2;
          this._elapsed = 0;
          this._startTime = 0;
          this._firstTick = false;
          this._speed = 1;
          if (d !== undefined && !Number.isNaN(d)) {
            this.initWithDuration(d);
          }
        }
        setStartTime(time) {
          time = time < 0 ? 0 : time > this._duration ? this._duration : time;
          this._startTime = time;
        }
        getElapsed() {
          return this._elapsed;
        }
        initWithDuration(d) {
          this._duration = d === 0 ? macro.FLT_EPSILON : d;
          this._elapsed = 0;
          this._firstTick = true;
          return true;
        }
        isDone() {
          return this._elapsed >= this._duration;
        }
        _cloneDecoration(action) {
          action._speed = this._speed;
        }
        step(dt) {
          if (this._paused || this._speed === 0) return;
          dt *= this._speed;
          if (this._firstTick) {
            this._elapsed = this._startTime;
          } else this._elapsed += dt;
          let t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
          t = t < 1 ? t : 1;
          this.update(t > 0 ? t : 0);
          if (this.isUnknownDuration() && !this._firstTick) {
            this._elapsed -= dt;
          }
          if (this._firstTick) {
            this._firstTick = false;
            if (this._startTime > 0) {
              this._startTime = 0;
            }
          }
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          this._elapsed = 0;
          this._firstTick = true;
        }
        getSpeed() {
          return this._speed;
        }
        setSpeed(speed) {
          this._speed = speed;
        }
        getDurationScaled() {
          return this._duration / this._speed;
        }
      }
      class Sequence extends ActionInterval {
        static _actionOneTwo(actionOne, actionTwo) {
          const sequence = new Sequence();
          sequence.initWithTwoActions(actionOne, actionTwo);
          return sequence;
        }
        constructor(actions) {
          super();
          this._actions = [];
          this._split = 0;
          this._last = 0;
          this._reversed = false;
          if (!actions || actions.length === 0) {
            return;
          }
          if (actions.length === 1) {
            actions.push(new DummyAction());
          }
          const last = actions.length - 1;
          if (last >= 0 && actions[last] == null) logID(1015);
          if (last >= 0) {
            let prev = actions[0];
            let action1;
            for (let i = 1; i < last; i++) {
              if (actions[i]) {
                action1 = prev;
                prev = Sequence._actionOneTwo(action1, actions[i]);
              }
            }
            this.initWithTwoActions(prev, actions[last]);
          }
        }
        initWithTwoActions(actionOne, actionTwo) {
          if (!actionOne || !actionTwo) {
            errorID(1025);
            return false;
          }
          const durationOne = actionOne.getDurationScaled();
          const durationTwo = actionTwo.getDurationScaled();
          const d = durationOne + durationTwo;
          this.initWithDuration(d);
          this._actions[0] = actionOne;
          this._actions[1] = actionTwo;
          return true;
        }
        clone() {
          const action = new Sequence();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
          return action;
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          if (this._actions.length === 0) {
            return;
          }
          this._split = this._actions[0].getDurationScaled() / this._duration;
          this._last = -1;
        }
        stop() {
          if (this._actions.length === 0) {
            return;
          }
          if (this._last !== -1) this._actions[this._last].stop();
          super.stop();
        }
        update(t) {
          const locActions = this._actions;
          if (locActions.length === 0) {
            return;
          }
          let new_t = 0;
          let found = 0;
          const locSplit = this._split;
          const locLast = this._last;
          if (t < locSplit) {
            new_t = locSplit !== 0 ? t / locSplit : 1;
            if (found === 0 && locLast === 1 && this._reversed) {
              const two = locActions[1];
              two.update(0);
              if (two.isUnknownDuration()) return;
              two.stop();
            }
          } else {
            const one = locActions[0];
            found = 1;
            new_t = locSplit === 1 ? 1 : (t - locSplit) / (1 - locSplit);
            if (locLast === -1) {
              one.startWithTarget(this.target);
              one.update(1);
              if (one.isUnknownDuration()) return;
              one.stop();
            }
            if (locLast === 0) {
              one.update(1);
              if (one.isUnknownDuration()) return;
              one.stop();
            }
          }
          const actionFound = locActions[found];
          if (locLast === found && actionFound.isDone()) return;
          if (locLast !== found) actionFound.startWithTarget(this.target);
          actionFound.update(new_t > 1 ? new_t % 1 : new_t);
          this._last = found;
        }
        reverse() {
          const action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
          this._cloneDecoration(action);
          action._reversed = true;
          return action;
        }
        updateOwner(owner) {
          if (this._actions.length < 2) {
            return;
          }
          const actionOne = this._actions[0];
          const actionTwo = this._actions[1];
          if (!actionTwo._owner) {
            actionTwo._owner = owner;
          }
          if (actionOne instanceof Sequence || actionOne instanceof Spawn) {
            actionOne.updateOwner(owner);
          } else if (!actionOne._owner) {
            actionOne._owner = owner;
          }
        }
        findAction(id) {
          for (let i = 0, len = this._actions.length; i < len; ++i) {
            let action = this._actions[i];
            if (action.getId() === id) {
              return action;
            }
            if (action instanceof Sequence || action instanceof Spawn) {
              action = action.findAction(id);
              if (action && action.getId() === id) {
                return action;
              }
            }
          }
          return null;
        }
        isUnknownDuration() {
          if (this._actions.length === 0) return false;
          const one = this._actions[0];
          const two = this._actions[1];
          if (this._last < 1) {
            return one.isUnknownDuration();
          }
          return two.isUnknownDuration();
        }
      }
      function sequence(actions) {
        return new Sequence(actions);
      }
      class Repeat extends ActionInterval {
        constructor(action, times) {
          super();
          this._times = 0;
          this._total = 0;
          this._nextDt = 0;
          this._actionInstant = false;
          this._innerAction = null;
          this.initWithAction(action, times);
        }
        initWithAction(action, times) {
          if (!action || times === undefined) {
            return false;
          }
          const duration = action.getDurationScaled() * 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;
        }
        clone() {
          const action = new Repeat();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          if (this._innerAction) {
            action.initWithAction(this._innerAction.clone(), this._times);
          }
          return action;
        }
        startWithTarget(target) {
          this._total = 0;
          this._nextDt = (this._innerAction ? this._innerAction.getDurationScaled() : 0) / this._duration;
          super.startWithTarget(target);
          if (this._innerAction) this._innerAction.startWithTarget(target);
        }
        stop() {
          if (this._innerAction) this._innerAction.stop();
          super.stop();
        }
        update(dt) {
          const locInnerAction = this._innerAction;
          const locDuration = this._duration;
          const locTimes = this._times;
          let locNextDt = this._nextDt;
          if (!locInnerAction) {
            return;
          }
          if (dt >= locNextDt) {
            while (dt > locNextDt && this._total < locTimes) {
              locInnerAction.update(1);
              if (locInnerAction.isUnknownDuration()) return;
              this._total++;
              locInnerAction.stop();
              locInnerAction.startWithTarget(this.target);
              locNextDt += locInnerAction.getDurationScaled() / locDuration;
              this._nextDt = locNextDt > 1 ? 1 : locNextDt;
            }
            if (dt >= 1.0 && this._total < locTimes) {
              locInnerAction.update(1);
              if (locInnerAction.isUnknownDuration()) return;
              this._total++;
            }
            if (!this._actionInstant) {
              if (this._total === locTimes) {
                locInnerAction.stop();
              } else {
                locInnerAction.update(dt - (locNextDt - locInnerAction.getDurationScaled() / locDuration));
              }
            }
          } else {
            locInnerAction.update(dt * locTimes % 1.0);
          }
        }
        isDone() {
          return this._total === this._times;
        }
        reverse() {
          const actionArg = this._innerAction ? this._innerAction.reverse() : undefined;
          const action = new Repeat(actionArg, this._times);
          this._cloneDecoration(action);
          return action;
        }
        setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        }
        getInnerAction() {
          return this._innerAction;
        }
        isUnknownDuration() {
          if (this._innerAction) {
            return this._innerAction.isUnknownDuration();
          }
          return false;
        }
      }
      function repeat(action, times) {
        return new Repeat(action, times);
      }
      class RepeatForever extends ActionInterval {
        constructor(action) {
          super();
          this._innerAction = null;
          if (action) this.initWithAction(action);
        }
        initWithAction(action) {
          if (!action) {
            errorID(1026);
            return false;
          }
          this._innerAction = action;
          this._duration = Infinity;
          return true;
        }
        clone() {
          const action = new RepeatForever();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          if (this._innerAction) {
            action.initWithAction(this._innerAction.clone());
          }
          return action;
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          if (this._innerAction) {
            this._innerAction.startWithTarget(target);
          }
        }
        stop() {
          if (this._innerAction) this._innerAction.stop();
          super.stop();
        }
        step(dt) {
          if (this._paused || this._speed === 0) return;
          const locInnerAction = this._innerAction;
          if (!locInnerAction) {
            return;
          }
          dt *= this._speed;
          locInnerAction.step(dt);
          if (locInnerAction.isDone()) {
            locInnerAction.startWithTarget(this.target);
            locInnerAction.step(locInnerAction.getElapsed() - locInnerAction.getDurationScaled());
          }
        }
        update(_t) {
          logID(1007);
        }
        isDone() {
          return false;
        }
        reverse() {
          if (this._innerAction) {
            const action = new RepeatForever(this._innerAction.reverse());
            this._cloneDecoration(action);
            return action;
          }
          return this;
        }
        setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        }
        getInnerAction() {
          return this._innerAction;
        }
        isUnknownDuration() {
          if (this._innerAction) {
            return this._innerAction.isUnknownDuration();
          }
          return false;
        }
      }
      function repeatForever(action) {
        return new RepeatForever(action);
      }
      class Spawn extends ActionInterval {
        static _actionOneTwo(action1, action2) {
          const spawn = new Spawn();
          spawn.initWithTwoActions(action1, action2);
          return spawn;
        }
        constructor(actions) {
          super();
          this._one = null;
          this._two = null;
          this._finished = false;
          if (!actions || actions.length === 0) {
            return;
          }
          if (actions.length === 1) {
            actions.push(new DummyAction());
          }
          const last = actions.length - 1;
          if (last >= 0 && actions[last] == null) logID(1015);
          if (last >= 0) {
            let prev = actions[0];
            let action1;
            for (let i = 1; i < last; i++) {
              if (actions[i]) {
                action1 = prev;
                prev = Spawn._actionOneTwo(action1, actions[i]);
              }
            }
            this.initWithTwoActions(prev, actions[last]);
          }
        }
        initWithTwoActions(action1, action2) {
          if (!action1 || !action2) {
            errorID(1027);
            return false;
          }
          let ret = false;
          const d1 = action1.getDurationScaled();
          const d2 = action2.getDurationScaled();
          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;
        }
        clone() {
          const action = new Spawn();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          if (this._one && this._two) {
            action.initWithTwoActions(this._one.clone(), this._two.clone());
          }
          return action;
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          if (this._one) this._one.startWithTarget(target);
          if (this._two) this._two.startWithTarget(target);
        }
        stop() {
          if (this._one) this._one.stop();
          if (this._two) this._two.stop();
          super.stop();
        }
        update(t) {
          if (this._one) {
            if (!this._finished || this._one.isUnknownDuration()) {
              this._one.update(t);
            }
          }
          if (this._two) {
            if (!this._finished || this._two.isUnknownDuration()) {
              this._two.update(t);
            }
          }
          this._finished = t === 1;
        }
        reverse() {
          if (this._one && this._two) {
            const action = Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
            this._cloneDecoration(action);
            return action;
          }
          return this;
        }
        updateOwner(owner) {
          if (!this._one || !this._two) {
            return;
          }
          if (!this._two._owner) {
            this._two._owner = owner;
          }
          const one = this._one;
          if (one instanceof Spawn || one instanceof Sequence) {
            one.updateOwner(owner);
          } else if (!one._owner) {
            one._owner = owner;
          }
        }
        findAction(id) {
          const one = this._one;
          const two = this._two;
          let foundAction = null;
          const find = action => {
            if (action.getId() === id) return action;
            if (action instanceof Sequence || action instanceof Spawn) {
              const found = action.findAction(id);
              if (found) return found;
            }
            return null;
          };
          if (one) {
            foundAction = find(one);
            if (foundAction) return foundAction;
          }
          if (two) {
            foundAction = find(two);
            if (foundAction) return foundAction;
          }
          return null;
        }
        isUnknownDuration() {
          const one = this._one;
          const two = this._two;
          if (one == null || two == null) return false;
          const isOneUnknownTime = one.isUnknownDuration();
          const isTwoUnknownTime = two.isUnknownDuration();
          if (isOneUnknownTime || isTwoUnknownTime) {
            if (isOneUnknownTime && isTwoUnknownTime) return true;else if (this._finished) return true;
          }
          return false;
        }
      }
      function spawn(actions) {
        return new Spawn(actions);
      }
      class DelayTime extends ActionInterval {
        update(_dt) {}
        reverse() {
          const action = new DelayTime(this._duration);
          this._cloneDecoration(action);
          return action;
        }
        clone() {
          const action = new DelayTime();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          action.initWithDuration(this._duration);
          return action;
        }
        isUnknownDuration() {
          return false;
        }
      }
      function delayTime(d) {
        return new DelayTime(d);
      }
      class ReverseTime extends ActionInterval {
        constructor(action) {
          super();
          this._other = null;
          if (action) this.initWithAction(action);
        }
        initWithAction(action) {
          if (!action) {
            errorID(1028);
            return false;
          }
          if (action === this._other) {
            errorID(1029);
            return false;
          }
          if (super.initWithDuration(action.getDurationScaled())) {
            this._other = action;
            return true;
          }
          return false;
        }
        clone() {
          const action = new ReverseTime();
          action._id = this._id;
          action._speed = this._speed;
          this._cloneDecoration(action);
          if (this._other) {
            action.initWithAction(this._other.clone());
          }
          return action;
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          if (this._other) this._other.startWithTarget(target);
        }
        update(dt) {
          if (this._other) this._other.update(1 - dt);
        }
        reverse() {
          if (this._other) {
            return this._other.clone();
          }
          return this;
        }
        stop() {
          if (this._other) this._other.stop();
          super.stop();
        }
        isUnknownDuration() {
          return false;
        }
      }
      function reverseTime(action) {
        return new ReverseTime(action);
      }
      class ActionCustomUpdate extends ActionInterval {
        constructor(duration, cb, args) {
          super(duration);
          this._cb = cb;
          this._args = args;
        }
        clone() {
          return new ActionCustomUpdate(this._duration, this._cb, this._args);
        }
        update(ratio) {
          this._cb(this.target, ratio, ...this._args);
        }
        reverse() {
          return this.clone();
        }
        isUnknownDuration() {
          return false;
        }
      }

      class ActionUnknownDuration extends FiniteTimeAction {
        constructor(cb, args) {
          super();
          this._finished = false;
          this._cb = cb;
          this._args = args;
        }
        clone() {
          return new ActionUnknownDuration(this._cb, this._args);
        }
        reverse() {
          return this.clone();
        }
        step(dt) {
          throw new Error('should never go here');
        }
        update(t) {
          const dt = cclegacy.game.deltaTime;
          this._finished = this._cb(this.target, dt, ...this._args);
        }
        isDone() {
          return this._finished;
        }
        isUnknownDuration() {
          return !this.isDone();
        }
      }

      function TweenEasingAdapter(easingName) {
        const initialChar = easingName.charAt(0);
        if (/[A-Z]/.test(initialChar)) {
          easingName = easingName.replace(initialChar, initialChar.toLowerCase());
          const arr = easingName.split('-');
          if (arr.length === 2) {
            const str0 = arr[0];
            if (str0 === 'linear') {
              easingName = 'linear';
            } else {
              const 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) {
        const header = ' [Tween:] ';
        const message = ` option is not support in v + ${engineVersion}`;
        const _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}`);
        }
      }
      class TweenAction extends ActionInterval {
        constructor(duration, props, opts) {
          super();
          this._reversed = false;
          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') {
              const easingName = opts.easing;
              opts.easing = easing[easingName];
              if (!opts.easing) {
                warnID(1031, easingName);
              }
            }
          }
          this._opts = opts;
          this._props = Object.create(null);
          for (const name in props) {
            var _value$legacyProgress;
            if (!props.hasOwnProperty(name)) continue;
            let value = props[name];
            if (typeof value === 'function') {
              value = value();
            } else if (value == null) {
              continue;
            }
            let customEasing;
            let customProgress;
            let customValue;
            if (value.value !== undefined) {
              customValue = value.value;
              if (typeof customValue === 'function') {
                customValue = customValue();
              }
              if (value.easing !== undefined) {
                if (typeof value.easing === 'string') {
                  customEasing = easing[value.easing];
                  if (!customEasing) warnID(1031, value.easing);
                } else {
                  customEasing = value.easing;
                }
              }
              if (value.progress !== undefined) {
                customProgress = value.progress;
              }
            } else {
              customValue = value;
            }
            const prop = Object.create(null);
            prop.start = prop.current = prop.end = null;
            prop.keys = null;
            prop.value = customValue;
            prop.easing = customEasing;
            prop.progress = customProgress;
            prop.convert = value.convert;
            prop.clone = value.clone;
            prop.add = value.add;
            prop.sub = value.sub;
            prop.legacyProgress = (_value$legacyProgress = value.legacyProgress) !== null && _value$legacyProgress !== void 0 ? _value$legacyProgress : true;
            prop.toFixed = value.toFixed;
            prop.onStart = value.onStart;
            prop.onStop = value.onStop;
            prop.onComplete = value.onComplete;
            prop.valid = true;
            this._props[name] = prop;
          }
          this._originProps = props;
          this.initWithDuration(duration);
        }
        get relative() {
          return !!this._opts.relative;
        }
        clone() {
          const action = new TweenAction(this._duration, this._originProps, this._opts);
          action._reversed = this._reversed;
          action._owner = this._owner;
          action._id = this._id;
          this._cloneDecoration(action);
          return action;
        }
        reverse() {
          if (!this._opts.relative) {
            warnID(16382);
            return new TweenAction(0, {});
          }
          const action = new TweenAction(this._duration, this._originProps, this._opts);
          this._cloneDecoration(action);
          action._reversed = !this._reversed;
          action._owner = this._owner;
          return action;
        }
        startWithTarget(target) {
          super.startWithTarget(target);
          const workerTarget = this._getWorkerTarget();
          if (!workerTarget) return;
          const relative = !!this._opts.relative;
          const props = this._props;
          const reversed = this._reversed;
          for (const property in props) {
            const _t = workerTarget[property];
            if (_t === undefined) {
              continue;
            }
            const prop = props[property];
            const value = prop.value;
            if (typeof _t === 'number') {
              prop.start = _t;
              prop.current = _t;
              prop.end = relative ? reversed ? _t - value : _t + value : value;
            } else if (typeof _t === 'object') {
              if (prop.legacyProgress) {
                if (prop.start == null) {
                  const Ctor = _t.constructor;
                  prop.start = new Ctor();
                  prop.current = new Ctor();
                  prop.end = new Ctor();
                }
                let propertyKeys;
                if (value.getModifiableProperties) {
                  propertyKeys = value.getModifiableProperties();
                } else {
                  propertyKeys = Object.keys(value);
                }
                prop.keys = propertyKeys;
                for (let i = 0, len = propertyKeys.length; i < len; ++i) {
                  const k = propertyKeys[i];
                  if (isNaN(_t[k])) continue;
                  prop.start[k] = _t[k];
                  prop.current[k] = _t[k];
                  prop.end[k] = relative ? reversed ? _t[k] - value[k] : _t[k] + value[k] : value[k];
                }
              } else {
                const clone = prop.clone;
                if (!clone) {
                  warnID(16383, property);
                  prop.valid = false;
                  continue;
                } else {
                  const add = prop.add;
                  const sub = prop.sub;
                  if (relative) {
                    if (!add) {
                      warnID(16384, property);
                      prop.valid = false;
                    }
                    if (reversed && !sub) {
                      warnID(16385, property);
                      prop.valid = false;
                    }
                    if (!prop.valid) continue;
                  }
                  prop.start = clone(_t);
                  prop.current = clone(_t);
                  prop.end = relative ? reversed ? sub(_t, value) : add(_t, value) : clone(value);
                }
              }
            } else if (typeof _t === 'string') {
              const convertFn = prop.convert;
              const convertToNumber = v => {
                if (typeof v === 'number') return v;
                let convertedValue = v;
                if (convertFn) {
                  convertedValue = convertFn(v);
                }
                if (typeof convertedValue !== 'number') {
                  convertedValue = Number(convertedValue);
                  if (Number.isNaN(convertedValue)) {
                    warnID(16386, `${v}`);
                    return null;
                  }
                }
                return convertedValue;
              };
              const targetNumValue = convertToNumber(value);
              const startNumValue = convertToNumber(_t);
              if (targetNumValue == null || startNumValue == null) {
                prop.valid = false;
                continue;
              }
              prop.start = startNumValue;
              prop.current = _t;
              prop.end = relative ? reversed ? startNumValue - targetNumValue : startNumValue + targetNumValue : targetNumValue;
            }
            if (prop.onStart) {
              prop.onStart({
                relative,
                reversed,
                start: prop.start,
                end: prop.end
              });
            }
          }
          if (this._opts.onStart) {
            this._opts.onStart(workerTarget);
          }
        }
        stop() {
          const props = this._props;
          for (const name in props) {
            const prop = props[name];
            if (!prop.valid) continue;
            if (prop.onStop) {
              prop.onStop();
            }
          }
          super.stop();
        }
        update(t) {
          const workerTarget = this._getWorkerTarget();
          if (!workerTarget) return;
          if (!this._opts) return;
          const props = this._props;
          const opts = this._opts;
          let easingTime = t;
          if (typeof opts.easing === 'function') easingTime = opts.easing(t);
          const progress = opts.progress;
          for (const name in props) {
            const prop = props[name];
            if (!prop.valid) continue;
            const time = prop.easing ? prop.easing(t) : easingTime;
            const interpolation = prop.progress ? prop.progress : progress;
            const start = prop.start;
            const end = prop.end;
            const current = prop.current;
            if (typeof current === 'number') {
              prop.current = interpolation(start, end, prop.current, time);
            } else if (typeof start === 'object') {
              if (prop.legacyProgress) {
                const keys = prop.keys;
                for (let i = 0, len = keys.length; i < len; ++i) {
                  const k = keys[i];
                  prop.current[k] = interpolation(start[k], end[k], prop.current[k], time);
                }
              } else {
                prop.current = interpolation(start, end, prop.current, time);
              }
            } else if (typeof current === 'string') {
              let newCurrent = interpolation(start, end, prop.current, time);
              if (typeof newCurrent === 'number') {
                var _prop$toFixed;
                newCurrent = newCurrent.toFixed((_prop$toFixed = prop.toFixed) !== null && _prop$toFixed !== void 0 ? _prop$toFixed : 0);
              } else if (typeof newCurrent !== 'string') {
                warnID(16387);
                continue;
              }
              prop.current = newCurrent;
            }
            workerTarget[name] = prop.current;
            if (t === 1 && prop.onComplete) {
              prop.onComplete();
            }
          }
          if (opts.onUpdate) {
            opts.onUpdate(workerTarget, t);
          }
          if (t === 1 && opts.onComplete) {
            opts.onComplete(workerTarget);
          }
        }
        progress(start, end, current, t) {
          return start + (end - start) * t;
        }
        isUnknownDuration() {
          return false;
        }
      } exports("TweenAction", TweenAction);

      class SetAction extends ActionInstant {
        constructor(props) {
          super();
          this._props = void 0;
          this._props = {};
          if (props) this.init(props);
        }
        init(props) {
          for (const name in props) {
            this._props[name] = props[name];
          }
          return true;
        }
        update() {
          const props = this._props;
          const target = this.target;
          for (const name in props) {
            target[name] = props[name];
          }
        }
        clone() {
          const action = new SetAction();
          action._id = this._id;
          action.init(this._props);
          return action;
        }
        isUnknownDuration() {
          return false;
        }
      }

      class Tween {
        constructor(target) {
          this._actions = [];
          this._finalAction = null;
          this._target = null;
          this._tag = -1;
          this._timeScale = 1;
          this._target = target === undefined ? null : target;
        }
        tag(tag) {
          this._tag = tag;
          return this;
        }
        id(id) {
          if (this._actions.length > 0) {
            this._actions[this._actions.length - 1].setId(id);
          }
          return this;
        }
        then(other) {
          const u = other._union(true);
          if (u) {
            u.setSpeed(other._timeScale);
            this._actions.push(u);
          }
          return this;
        }
        reverse(otherTweenOrId, id) {
          if (otherTweenOrId == null && id == null) {
            return this.reverseTween();
          }
          let tweenForFindAction;
          let actionId;
          if (otherTweenOrId instanceof Tween) {
            tweenForFindAction = otherTweenOrId;
            if (id !== undefined) {
              actionId = id;
            }
          } else if (typeof otherTweenOrId === 'number') {
            tweenForFindAction = this;
            actionId = otherTweenOrId;
          }
          if (tweenForFindAction) {
            const reversedAction = Tween.reverseAction(tweenForFindAction, actionId);
            if (reversedAction) {
              this._actions.push(reversedAction);
            }
          }
          return this;
        }
        reverseTween() {
          if (this._actions.length === 0) {
            warnID(16388);
            return this.clone(this._target);
          }
          const action = this._union(false);
          const r = tween(this._target);
          r._timeScale = this._timeScale;
          if (action) r.insertAction(action.reverse());
          return r;
        }
        static reverseAction(t, actionId) {
          const actions = t._actions;
          if (actions.length === 0) return null;
          let action = null;
          let reversedAction = null;
          if (typeof actionId === 'number') {
            action = t.findAction(actionId, actions);
          } else if (t) {
            action = t._union(false);
          }
          if (action) {
            reversedAction = action.reverse();
            reversedAction._owner = t;
          } else {
            warnID(16391, `${actionId}`);
          }
          return reversedAction;
        }
        findAction(id, actions) {
          let action = null;
          for (let i = 0, len = actions.length; i < len; ++i) {
            action = actions[i];
            if (action.getId() === id) return action;
            if (action instanceof Sequence || action instanceof Spawn) {
              action = action.findAction(id);
              if (action) return action;
            }
          }
          return null;
        }
        insertAction(other) {
          const action = other.clone();
          this.updateOwnerForAction(action);
          this._actions.push(action);
          return this;
        }
        updateOwnerForAction(action) {
          if (!action) return;
          if (action instanceof Sequence || action instanceof Spawn) {
            action.updateOwner(this);
          } else if (!action._owner) {
            action._owner = this;
          }
        }
        target(target) {
          this._target = target;
          return this;
        }
        getTarget() {
          return this._target;
        }
        start(time = 0) {
          if (!this._target) {
            warnID(16392);
            return this;
          }
          if (this._finalAction) {
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
          }
          const final = this._unionForStart();
          this._finalAction = final;
          if (final) {
            final.setTag(this._tag);
            final.setSpeed(this._timeScale);
            final.setStartTime(time);
            final.setPaused(false);
            TweenSystem.instance.ActionManager.addAction(final, this._target, false);
          } else {
            warnID(16393);
          }
          return this;
        }
        stop() {
          if (this._finalAction) {
            this._finalAction.stop();
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
            this._finalAction = null;
          }
          return this;
        }
        pause() {
          if (this._finalAction) {
            this._finalAction.setPaused(true);
          } else {
            warnID(16389);
          }
          return this;
        }
        resume() {
          if (this._finalAction) {
            this._finalAction.setPaused(false);
          } else {
            warnID(16390);
          }
          return this;
        }
        get running() {
          if (this._finalAction) {
            return TweenSystem.instance.ActionManager.isActionRunning(this._finalAction);
          }
          return false;
        }
        clone(target) {
          const action = this._union(false);
          const r = tween(target !== null && target !== void 0 ? target : this._target);
          r._timeScale = this._timeScale;
          return action ? r.insertAction(action) : r;
        }
        union(fromId) {
          const unionAll = () => {
            const action = this._union(false);
            this._actions.length = 0;
            if (action) this._actions.push(action);
          };
          if (fromId === undefined) {
            unionAll();
            return this;
          }
          const actions = this._actions;
          const index = actions.findIndex(action => action.getId() === fromId);
          const len = actions.length;
          if (len > 1) {
            const actionsToUnion = actions.splice(index);
            if (actionsToUnion.length === 1) {
              actions.push(actionsToUnion[0]);
            } else {
              actions.push(sequence(actionsToUnion));
            }
          }
          return this;
        }
        to(duration, props, opts) {
          const options = opts || Object.create(null);
          options.relative = false;
          const action = new TweenAction(duration, props, options);
          this._actions.push(action);
          return this;
        }
        by(duration, props, opts) {
          const options = opts || Object.create(null);
          options.relative = true;
          const action = new TweenAction(duration, props, options);
          this._actions.push(action);
          return this;
        }
        update(duration, cb, ...args) {
          const action = new ActionCustomUpdate(duration, cb, args);
          this._actions.push(action);
          return this;
        }
        updateUntil(cb, ...args) {
          const action = new ActionUnknownDuration(cb, args);
          this._actions.push(action);
          return this;
        }
        set(props) {
          const action = new SetAction(props);
          this._actions.push(action);
          return this;
        }
        delay(duration) {
          const action = delayTime(duration);
          this._actions.push(action);
          return this;
        }
        call(callback, callbackThis, data) {
          const action = callFunc(callback, callbackThis, data);
          this._actions.push(action);
          return this;
        }
        sequence(...args) {
          const action = Tween._wrappedSequence(args);
          if (action) this._actions.push(action);
          return this;
        }
        parallel(...args) {
          const action = Tween._wrappedParallel(args);
          if (action) this._actions.push(action);
          return this;
        }
        timeScale(scale) {
          this._timeScale = scale;
          if (this._finalAction) {
            this._finalAction.setSpeed(scale);
          }
          return this;
        }
        getTimeScale() {
          return this._timeScale;
        }
        get duration() {
          if (this._finalAction) {
            return this._finalAction.getDuration();
          }
          return 0;
        }
        repeat(repeatTimes, embedTween) {
          if (repeatTimes === Infinity) {
            return this.repeatForever(embedTween);
          }
          const actions = this._actions;
          let action;
          if (embedTween instanceof Tween) {
            action = embedTween._union(false);
          } else {
            action = actions.pop();
          }
          if (action) actions.push(repeat(action, repeatTimes));
          return this;
        }
        repeatForever(embedTween) {
          const actions = this._actions;
          let action;
          if (embedTween instanceof Tween) {
            action = embedTween._union(false);
          } else {
            action = actions.pop();
          }
          if (action && actions.length !== 0) {
            actions.push(repeat(action, Number.MAX_SAFE_INTEGER));
          } else if (action instanceof ActionInterval) {
            actions.push(repeatForever(action));
          } else {
            warnID(16394);
          }
          return this;
        }
        reverseTime(embedTween) {
          const actions = this._actions;
          let action;
          if (embedTween instanceof Tween) {
            action = embedTween._union(false);
          } else {
            action = actions.pop();
          }
          if (action instanceof ActionInterval) {
            actions.push(reverseTime(action));
          } else {
            warnID(16395);
          }
          return this;
        }
        hide() {
          const isNode = this._target instanceof Node$1;
          if (isNode) {
            const action = hide();
            this._actions.push(action);
          }
          return this;
        }
        show() {
          const isNode = this._target instanceof Node$1;
          if (isNode) {
            const action = show();
            this._actions.push(action);
          }
          return this;
        }
        removeSelf() {
          const isNode = this._target instanceof Node$1;
          if (isNode) {
            const action = removeSelf(false);
            this._actions.push(action);
          }
          return this;
        }
        destroySelf() {
          const isNode = this._target instanceof Node$1;
          if (isNode) {
            const action = removeSelf(true);
            this._actions.push(action);
          }
          return this;
        }
        static getRunningCount(target) {
          return TweenSystem.instance.ActionManager.getNumberOfRunningActionsInTarget(target);
        }
        static stopAll() {
          TweenSystem.instance.ActionManager.removeAllActions();
        }
        static stopAllByTag(tag, target) {
          TweenSystem.instance.ActionManager.removeAllActionsByTag(tag, target);
        }
        static stopAllByTarget(target) {
          TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target);
        }
        static pauseAllByTarget(target) {
          TweenSystem.instance.ActionManager.pauseTarget(target);
        }
        static resumeAllByTarget(target) {
          TweenSystem.instance.ActionManager.resumeTarget(target);
        }
        _union(needUpdateOwner) {
          const actions = this._actions;
          if (actions.length === 0) return null;
          const action = sequence(actions);
          if (needUpdateOwner) {
            this.updateOwnerForAction(action);
          }
          return action;
        }
        _unionForStart() {
          const actions = this._actions;
          if (actions.length === 0) return null;
          let action;
          if (actions.length === 1 && actions[0] instanceof RepeatForever) {
            action = actions[0];
          } else {
            action = sequence(actions);
          }
          return action;
        }
        static _tweenToActions(args) {
          const tmpArgs = Tween._tmpArgs;
          tmpArgs.length = 0;
          for (let l = args.length, i = 0; i < l; i++) {
            const t = args[i];
            const action = t._union(true);
            if (action) {
              action.setSpeed(t._timeScale);
              tmpArgs.push(action);
            }
          }
        }
        static _wrappedSequence(args) {
          Tween._tweenToActions(args);
          const ret = sequence(Tween._tmpArgs);
          this._tmpArgs.length = 0;
          return ret;
        }
        static _wrappedParallel(args) {
          Tween._tweenToActions(args);
          const ret = spawn(Tween._tmpArgs);
          this._tmpArgs.length = 0;
          return ret;
        }
      } exports("Tween", Tween);
      Tween._tmpArgs = [];
      legacyCC.Tween = Tween;
      function tween(target) {
        return new Tween(target);
      }
      legacyCC.tween = tween;
      function tweenUtil(target) {
        warnID(16396);
        return new Tween(target);
      }
      legacyCC.tweenUtil = tweenUtil;

      var _dec$k, _dec2$h, _dec3$g, _dec4$c, _dec5$c, _dec6$6, _dec7$4, _dec8$3, _dec9$3, _dec10$1, _class$k, _class2$h, _initializer$h, _initializer2$f, _initializer3$c, _initializer4$b, _initializer5$9, _initializer6$6, _initializer7$6, _initializer8$6, _initializer9$6, _initializer10$6, _initializer11$6, _initializer12$5, _initializer13$3, _initializer14$2, _class3$c;
      const _tempColor$1 = new Color$1();
      const Transition = {
        "NONE": 0,
        "COLOR": 1,
        "SPRITE": 2,
        "SCALE": 3
      };
      ccenum(Transition);
      const ButtonEventType = {
        "CLICK": "click"
      };
      let Button = (_dec$k = ccclass$H('cc.Button'), _dec2$h = executionOrder$1(110), _dec3$g = requireComponent(UITransform), _dec4$c = type$a(Node$1), _dec5$c = type$a(Transition), _dec6$6 = type$a(SpriteFrame), _dec7$4 = type$a(SpriteFrame), _dec8$3 = type$a(SpriteFrame), _dec9$3 = type$a(SpriteFrame), _dec10$1 = type$a([EventHandler]), _dec$k(_class$k = _dec2$h(_class$k = _dec3$g(_class$k = (_class2$h = (_class3$c = class Button extends Component {
        get target() {
          return this._target || this.node;
        }
        set target(value) {
          if (this._target === value) {
            return;
          }
          if (this._target) {
            this._unregisterTargetEvent(this._target);
          }
          this._target = value;
          this._applyTarget();
        }
        get interactable() {
          return this._interactable;
        }
        set interactable(value) {
          if (this._interactable === value) {
            return;
          }
          this._interactable = value;
          this._updateState();
          if (!this._interactable) {
            this._resetState();
          }
        }
        set _resizeToTarget(value) {
          if (value) {
            this._resizeNodeToTargetNode();
          }
        }
        get transition() {
          return this._transition;
        }
        set transition(value) {
          if (this._transition === value) {
            return;
          }
          if (this._transition === 1) {
            this._updateColorTransition(0);
          } else if (this._transition === 2) {
            this._updateSpriteTransition(0);
          }
          this._transition = value;
          this._updateState();
        }
        get normalColor() {
          return this._normalColor;
        }
        set normalColor(value) {
          if (this._normalColor === value) {
            return;
          }
          this._normalColor.set(value);
          this._updateState();
        }
        get pressedColor() {
          return this._pressedColor;
        }
        set pressedColor(value) {
          if (this._pressedColor === value) {
            return;
          }
          this._pressedColor.set(value);
        }
        get hoverColor() {
          return this._hoverColor;
        }
        set hoverColor(value) {
          if (this._hoverColor === value) {
            return;
          }
          this._hoverColor.set(value);
        }
        get disabledColor() {
          return this._disabledColor;
        }
        set disabledColor(value) {
          if (this._disabledColor === value) {
            return;
          }
          this._disabledColor.set(value);
          this._updateState();
        }
        get duration() {
          return this._duration;
        }
        set duration(value) {
          if (this._duration === value) {
            return;
          }
          this._duration = value;
        }
        get zoomScale() {
          return this._zoomScale;
        }
        set zoomScale(value) {
          if (this._zoomScale === value) {
            return;
          }
          this._zoomScale = value;
        }
        get normalSprite() {
          return this._normalSprite;
        }
        set normalSprite(value) {
          if (this._normalSprite === value) {
            return;
          }
          this._normalSprite = value;
          const sprite = this.node.getComponent(Sprite);
          if (sprite) {
            sprite.spriteFrame = value;
          }
          this._updateState();
        }
        get pressedSprite() {
          return this._pressedSprite;
        }
        set pressedSprite(value) {
          if (this._pressedSprite === value) {
            return;
          }
          this._pressedSprite = value;
          this._updateState();
        }
        get hoverSprite() {
          return this._hoverSprite;
        }
        set hoverSprite(value) {
          if (this._hoverSprite === value) {
            return;
          }
          this._hoverSprite = value;
          this._updateState();
        }
        get disabledSprite() {
          return this._disabledSprite;
        }
        set disabledSprite(value) {
          if (this._disabledSprite === value) {
            return;
          }
          this._disabledSprite = value;
          this._updateState();
        }
        constructor() {
          super();
          this.clickEvents = _initializer$h && _initializer$h();
          this._interactable = _initializer2$f && _initializer2$f();
          this._transition = _initializer3$c && _initializer3$c();
          this._normalColor = _initializer4$b && _initializer4$b();
          this._hoverColor = _initializer5$9 && _initializer5$9();
          this._pressedColor = _initializer6$6 && _initializer6$6();
          this._disabledColor = _initializer7$6 && _initializer7$6();
          this._normalSprite = _initializer8$6 && _initializer8$6();
          this._hoverSprite = _initializer9$6 && _initializer9$6();
          this._pressedSprite = _initializer10$6 && _initializer10$6();
          this._disabledSprite = _initializer11$6 && _initializer11$6();
          this._duration = _initializer12$5 && _initializer12$5();
          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 = v3();
          this._toScale = v3();
          this._originalScale = null;
          this._sprite = null;
          this._targetScale = v3();
        }
        __preload() {
          if (!this.target) {
            this.target = this.node;
          }
          this._applyTarget();
          this._resetState();
        }
        onEnable() {
          {
            this._registerNodeEvent();
          }
        }
        onDisable() {
          this._resetState();
          {
            this._unregisterNodeEvent();
          }
        }
        onDestroy() {
          if (this.target.isValid) {
            this._unregisterTargetEvent(this.target);
          }
        }
        update(dt) {
          const target = this.target;
          if (this._transitionFinished || !target) {
            return;
          }
          if (this._transition !== 1 && this._transition !== 3) {
            return;
          }
          this._time += dt;
          let ratio = 1.0;
          if (this._duration > 0) {
            ratio = this._time / this._duration;
          }
          if (ratio >= 1) {
            ratio = 1;
          }
          if (this._transition === 1) {
            const renderComp = target._uiProps.uiComp;
            Color$1.lerp(_tempColor$1, this._fromColor, this._toColor, ratio);
            if (renderComp) {
              renderComp.color = _tempColor$1;
            }
          } else if (this.transition === 3) {
            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;
          }
        }
        _resizeNodeToTargetNode() {
          if (!this.target) {
            return;
          }
          this.target._uiProps.uiTransformComp;
        }
        _resetState() {
          this._pressed = false;
          this._hovered = false;
          const target = this.target;
          if (!target) {
            return;
          }
          const transition = this._transition;
          if (transition === 1 && this._interactable) {
            const renderComp = target.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.color = this._normalColor;
            }
          } else if (transition === 3 && this._originalScale) {
            target.setScale(this._originalScale);
          }
          this._transitionFinished = true;
        }
        _registerNodeEvent() {
          this.node.on("touch-start", this._onTouchBegan, this);
          this.node.on("touch-move", this._onTouchMove, this);
          this.node.on("touch-end", this._onTouchEnded, this);
          this.node.on("touch-cancel", this._onTouchCancel, this);
          this.node.on("mouse-enter", this._onMouseMoveIn, this);
          this.node.on("mouse-leave", this._onMouseMoveOut, this);
          this.node.on("xrui-hover-entered", this._xrHoverEnter, this);
          this.node.on("xrui-hover-exited", this._xrHoverExit, this);
          this.node.on("xrui-click", this._xrClick, this);
          this.node.on("xrui-unclick", this._xrUnClick, this);
        }
        _registerTargetEvent(target) {
          target.on("transform-changed", this._onTargetTransformChanged, this);
        }
        _unregisterNodeEvent() {
          this.node.off("touch-start", this._onTouchBegan, this);
          this.node.off("touch-move", this._onTouchMove, this);
          this.node.off("touch-end", this._onTouchEnded, this);
          this.node.off("touch-cancel", this._onTouchCancel, this);
          this.node.off("mouse-enter", this._onMouseMoveIn, this);
          this.node.off("mouse-leave", this._onMouseMoveOut, this);
          this.node.off("xrui-hover-entered", this._xrHoverEnter, this);
          this.node.off("xrui-hover-exited", this._xrHoverExit, this);
          this.node.off("xrui-click", this._xrClick, this);
          this.node.off("xrui-unclick", this._xrUnClick, this);
        }
        _unregisterTargetEvent(target) {
          target.off("transform-changed");
        }
        _getTargetSprite(target) {
          let sprite = null;
          if (target) {
            sprite = target.getComponent(Sprite);
          }
          return sprite;
        }
        _applyTarget() {
          if (this.target) {
            this._sprite = this._getTargetSprite(this.target);
            if (!this._originalScale) {
              this._originalScale = new Vec3();
            }
            Vec3.copy(this._originalScale, this.target.scale);
            this._registerTargetEvent(this.target);
          }
        }
        _onTargetSpriteFrameChanged(comp) {
          if (this._transition === 2) {
            this._setCurrentStateSpriteFrame(comp.spriteFrame);
          }
        }
        _setCurrentStateSpriteFrame(spriteFrame) {
          if (!spriteFrame) {
            return;
          }
          switch (this._getButtonState()) {
            case 0:
              this._normalSprite = spriteFrame;
              break;
            case 1:
              this._hoverSprite = spriteFrame;
              break;
            case 2:
              this._pressedSprite = spriteFrame;
              break;
            case 3:
              this._disabledSprite = spriteFrame;
              break;
          }
        }
        _onTargetColorChanged(color) {
          if (this._transition === 1) {
            this._setCurrentStateColor(color);
          }
        }
        _setCurrentStateColor(color) {
          switch (this._getButtonState()) {
            case 0:
              this._normalColor = color;
              break;
            case 1:
              this._hoverColor = color;
              break;
            case 2:
              this._pressedColor = color;
              break;
            case 3:
              this._disabledColor = color;
              break;
          }
        }
        _onTargetTransformChanged(transformBit) {
          if (transformBit & 4 && this._originalScale && this._transition === 3 && this._transitionFinished) {
            Vec3.copy(this._originalScale, this.target.scale);
          }
        }
        _onTouchBegan(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        }
        _onTouchMove(event) {
          if (!this._interactable || !this.enabledInHierarchy || !this._pressed) {
            return;
          }
          if (!event) {
            return;
          }
          const touch = event.touch;
          if (!touch) {
            return;
          }
          const hit = this.node._uiProps.uiTransformComp.hitTest(touch.getLocation(), event.windowId);
          if (this._transition === 3 && 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 {
            let state;
            if (hit) {
              state = 2;
            } else {
              state = 0;
            }
            this._applyTransition(state);
          }
          if (event) {
            event.propagationStopped = true;
          }
        }
        _onTouchEnded(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, event);
            this.node.emit("click", this);
          }
          this._pressed = false;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        }
        _onTouchCancel(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = false;
          this._updateState();
        }
        _onMouseMoveIn(event) {
          if (this._pressed || !this.interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._transition === 2 && !this._hoverSprite) {
            return;
          }
          if (!this._hovered) {
            this._hovered = true;
            this._updateState();
          }
        }
        _onMouseMoveOut(event) {
          if (this._hovered) {
            this._hovered = false;
            this._updateState();
          }
        }
        _updateState() {
          const state = this._getButtonState();
          this._applyTransition(state);
        }
        _getButtonState() {
          let state = 0;
          if (!this._interactable) {
            state = 3;
          } else if (this._pressed) {
            state = 2;
          } else if (this._hovered) {
            state = 1;
          }
          return state;
        }
        _updateColorTransition(state) {
          var _this$target;
          const color = this._getColorByState(state);
          const renderComp = (_this$target = this.target) === null || _this$target === void 0 ? void 0 : _this$target.getComponent(UIRenderer);
          if (!renderComp) {
            return;
          }
          if (state === 3) {
            renderComp.color = color;
            this._transitionFinished = true;
          } else {
            this._fromColor = renderComp.color.clone();
            this._toColor = color;
            this._time = 0;
            this._transitionFinished = false;
          }
        }
        _updateSpriteTransition(state) {
          const sprite = this._getSpriteFrameByState(state);
          if (this._sprite && sprite) {
            this._sprite.spriteFrame = sprite;
          }
        }
        _updateScaleTransition(state) {
          if (!this._interactable) {
            return;
          }
          if (state === 2) {
            this._zoomUp();
          } else {
            this._zoomBack();
          }
        }
        _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;
        }
        _zoomBack() {
          if (!this.target || !this._originalScale) {
            return;
          }
          Vec3.copy(this._fromScale, this.target.scale);
          Vec3.copy(this._toScale, this._originalScale);
          this._time = 0;
          this._transitionFinished = false;
        }
        _applyTransition(state) {
          const transition = this._transition;
          if (transition === 1) {
            this._updateColorTransition(state);
          } else if (transition === 2) {
            this._updateSpriteTransition(state);
          } else if (transition === 3) {
            this._updateScaleTransition(state);
          }
        }
        _getSpriteFrameByState(state) {
          switch (state) {
            case 0:
              return this._normalSprite;
            case 3:
              return this._disabledSprite;
            case 1:
              return this.hoverSprite;
            case 2:
              return this._pressedSprite;
            default:
              {
                warn('Button._getColorByState(): wrong state.');
              }
              return null;
          }
        }
        _getColorByState(state) {
          switch (state) {
            case 0:
              return this._normalColor;
            case 3:
              return this._disabledColor;
            case 1:
              return this._hoverColor;
            case 2:
              return this._pressedColor;
            default:
              {
                warn('Button._getColorByState(): wrong state.');
              }
              return new Color$1();
          }
        }
        _xrHoverEnter() {
          this._onMouseMoveIn();
          this._updateState();
        }
        _xrHoverExit() {
          this._onMouseMoveOut();
          if (this._pressed) {
            this._pressed = false;
            this._updateState();
          }
        }
        _xrClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
        }
        _xrUnClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, this);
            this.node.emit("click", this);
          }
          this._pressed = false;
          this._updateState();
        }
      }, _class3$c.Transition = Transition, _class3$c.EventType = ButtonEventType, _class3$c), (_applyDecoratedDescriptor(_class2$h.prototype, "target", [_dec4$c], Object.getOwnPropertyDescriptor(_class2$h.prototype, "target"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "transition", [_dec5$c], Object.getOwnPropertyDescriptor(_class2$h.prototype, "transition"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "normalSprite", [_dec6$6], Object.getOwnPropertyDescriptor(_class2$h.prototype, "normalSprite"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "pressedSprite", [_dec7$4], Object.getOwnPropertyDescriptor(_class2$h.prototype, "pressedSprite"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "hoverSprite", [_dec8$3], Object.getOwnPropertyDescriptor(_class2$h.prototype, "hoverSprite"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "disabledSprite", [_dec9$3], Object.getOwnPropertyDescriptor(_class2$h.prototype, "disabledSprite"), _class2$h.prototype), _initializer$h = applyDecoratedInitializer(_class2$h.prototype, "clickEvents", [_dec10$1, serializable$l], function () {
        return [];
      }), _initializer2$f = applyDecoratedInitializer(_class2$h.prototype, "_interactable", [serializable$l], function () {
        return true;
      }), _initializer3$c = applyDecoratedInitializer(_class2$h.prototype, "_transition", [serializable$l], function () {
        return 0;
      }), _initializer4$b = applyDecoratedInitializer(_class2$h.prototype, "_normalColor", [serializable$l], function () {
        return Color$1.WHITE.clone();
      }), _initializer5$9 = applyDecoratedInitializer(_class2$h.prototype, "_hoverColor", [serializable$l], function () {
        return new Color$1(211, 211, 211, 255);
      }), _initializer6$6 = applyDecoratedInitializer(_class2$h.prototype, "_pressedColor", [serializable$l], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$6 = applyDecoratedInitializer(_class2$h.prototype, "_disabledColor", [serializable$l], function () {
        return new Color$1(124, 124, 124, 255);
      }), _initializer8$6 = applyDecoratedInitializer(_class2$h.prototype, "_normalSprite", [serializable$l], function () {
        return null;
      }), _initializer9$6 = applyDecoratedInitializer(_class2$h.prototype, "_hoverSprite", [serializable$l], function () {
        return null;
      }), _initializer10$6 = applyDecoratedInitializer(_class2$h.prototype, "_pressedSprite", [serializable$l], function () {
        return null;
      }), _initializer11$6 = applyDecoratedInitializer(_class2$h.prototype, "_disabledSprite", [serializable$l], function () {
        return null;
      }), _initializer12$5 = applyDecoratedInitializer(_class2$h.prototype, "_duration", [serializable$l], function () {
        return 0.1;
      }), _initializer13$3 = applyDecoratedInitializer(_class2$h.prototype, "_zoomScale", [serializable$l], function () {
        return 1.2;
      }), _initializer14$2 = applyDecoratedInitializer(_class2$h.prototype, "_target", [serializable$l], function () {
        return null;
      })), _class2$h)) || _class$k) || _class$k) || _class$k); exports({ Button: Button, ButtonComponent: Button });
      legacyCC.Button = Button;

      class EditBoxImplBase {
        constructor() {
          this._editing = false;
          this._delegate = null;
        }
        init(delegate) {}
        onEnable() {}
        beforeDraw() {}
        onDisable() {
          if (this._editing) {
            this.endEditing();
          }
        }
        clear() {
          this._delegate = null;
        }
        setTabIndex(index) {}
        setSize(width, height) {}
        setFocus(value) {
          if (value) {
            this.beginEditing();
          } else {
            this.endEditing();
          }
        }
        isFocused() {
          return this._editing;
        }
        beginEditing() {}
        endEditing() {}
      }

      ccwindow$1.document;
      new Mat4();
      new Mat4();
      new Vec3();
      let _domCount = 0;
      class EditBoxImpl extends EditBoxImplBase {
        constructor() {
          super();
          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}`;
          this._forceUpdate = false;
        }
        init(delegate) {
          return;
        }
        clear() {
          return;
        }
        _resize() {
          this._forceUpdate = true;
        }
        beforeDraw() {
          return;
        }
        setTabIndex(index) {
          return;
        }
        setSize(width, height) {
          return;
        }
        beginEditing() {
          return;
        }
        endEditing() {
          return;
        }
        _createInput() {
          return;
        }
        _createTextArea() {
          return;
        }
        _addDomToGameContainer() {
          return;
        }
        _removeDomFromGameContainer() {
          return;
        }
        _showDom() {
          return;
        }
        _hideDom() {
          return;
        }
        _showDomOnMobile() {
          return;
        }
        _hideDomOnMobile() {
          return;
        }
        _isElementInViewport() {
          return false;
        }
        _adjustWindowScroll() {
          return;
        }
        _scrollBackWindow() {
          return;
        }
        _updateMatrix() {
          return;
        }
        _updateInputType() {
          return;
        }
        _updateMaxLength() {
          return;
        }
        _initStyleSheet() {
          return;
        }
        _updateStyleSheet() {
          return;
        }
        _updateTextLabel(textLabel) {
          return;
        }
        _updatePlaceholderLabel(placeholderLabel) {
          return;
        }
        _registerEventListeners() {
          return;
        }
        _removeEventListeners() {
          return;
        }
      }

      const KeyboardReturnType = {
        "DEFAULT": 0,
        "DONE": 1,
        "SEND": 2,
        "SEARCH": 3,
        "GO": 4,
        "NEXT": 5
      };
      Enum(KeyboardReturnType);
      const InputMode = {
        "ANY": 0,
        "EMAIL_ADDR": 1,
        "NUMERIC": 2,
        "PHONE_NUMBER": 3,
        "URL": 4,
        "DECIMAL": 5,
        "SINGLE_LINE": 6
      };
      Enum(InputMode);
      const InputFlag = {
        "PASSWORD": 0,
        "SENSITIVE": 1,
        "INITIAL_CAPS_WORD": 2,
        "INITIAL_CAPS_SENTENCE": 3,
        "INITIAL_CAPS_ALL_CHARACTERS": 4,
        "DEFAULT": 5
      };
      Enum(InputFlag);

      var _dec$j, _dec2$g, _dec3$f, _dec4$b, _dec5$b, _dec6$5, _dec7$3, _dec8$2, _dec9$2, _dec10, _dec11, _dec12, _dec13, _class$j, _class2$g, _initializer$g, _initializer2$e, _initializer3$b, _initializer4$a, _initializer5$8, _initializer6$5, _initializer7$5, _initializer8$5, _initializer9$5, _initializer10$5, _initializer11$5, _initializer12$4, _initializer13$2, _class3$b;
      const LEFT_PADDING = 2;
      function capitalize(str) {
        return str.replace(/(?:^|\s)\S/g, a => a.toUpperCase());
      }
      function capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
      }
      const EditBoxEventType = {
        "EDITING_DID_BEGAN": "editing-did-began",
        "EDITING_DID_ENDED": "editing-did-ended",
        "TEXT_CHANGED": "text-changed",
        "EDITING_RETURN": "editing-return",
        "XR_EDITING_DID_BEGAN": "xr-editing-did-began",
        "XR_EDITING_DID_ENDED": "xr-editing-did-ended"
      };
      let EditBox = (_dec$j = ccclass$H('cc.EditBox'), _dec2$g = executionOrder$1(110), _dec3$f = requireComponent(UITransform), _dec4$b = type$a(Label), _dec5$b = type$a(Label), _dec6$5 = type$a(SpriteFrame), _dec7$3 = type$a(InputFlag), _dec8$2 = type$a(InputMode), _dec9$2 = type$a(KeyboardReturnType), _dec10 = type$a([EventHandler]), _dec11 = type$a([EventHandler]), _dec12 = type$a([EventHandler]), _dec13 = type$a([EventHandler]), _dec$j(_class$j = _dec2$g(_class$j = _dec3$f(_class$j = (_class2$g = (_class3$b = class EditBox extends Component {
        get string() {
          return this._string;
        }
        set string(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);
        }
        get placeholder() {
          if (!this._placeholderLabel) {
            return '';
          }
          return this._placeholderLabel.string;
        }
        set placeholder(value) {
          if (this._placeholderLabel) {
            this._placeholderLabel.string = value;
          }
        }
        get textLabel() {
          return this._textLabel;
        }
        set textLabel(oldValue) {
          if (this._textLabel !== oldValue) {
            this._textLabel = oldValue;
            if (this._textLabel) {
              this._updateTextLabel();
              this._updateLabels();
            }
          }
        }
        get placeholderLabel() {
          return this._placeholderLabel;
        }
        set placeholderLabel(oldValue) {
          if (this._placeholderLabel !== oldValue) {
            this._placeholderLabel = oldValue;
            if (this._placeholderLabel) {
              this._updatePlaceholderLabel();
              this._updateLabels();
            }
          }
        }
        get backgroundImage() {
          return this._backgroundImage;
        }
        set backgroundImage(value) {
          if (this._backgroundImage === value) {
            return;
          }
          this._backgroundImage = value;
          this._ensureBackgroundSprite();
          this._background.spriteFrame = value;
        }
        get inputFlag() {
          return this._inputFlag;
        }
        set inputFlag(value) {
          if (this._inputFlag === value) {
            return;
          }
          this._inputFlag = value;
          this._updateString(this._string);
        }
        get inputMode() {
          return this._inputMode;
        }
        set inputMode(oldValue) {
          if (this._inputMode !== oldValue) {
            this._inputMode = oldValue;
            this._updateTextLabel();
            this._updatePlaceholderLabel();
          }
        }
        get returnType() {
          return this._returnType;
        }
        set returnType(value) {
          this._returnType = value;
        }
        get maxLength() {
          return this._maxLength;
        }
        set maxLength(value) {
          this._maxLength = value;
        }
        get tabIndex() {
          return this._tabIndex;
        }
        set tabIndex(value) {
          if (this._tabIndex !== value) {
            this._tabIndex = value;
            if (this._impl) {
              this._impl.setTabIndex(value);
            }
          }
        }
        constructor() {
          super();
          this.editingDidBegan = _initializer$g && _initializer$g();
          this.textChanged = _initializer2$e && _initializer2$e();
          this.editingDidEnded = _initializer3$b && _initializer3$b();
          this.editingReturn = _initializer4$a && _initializer4$a();
          this._impl = null;
          this._background = null;
          this._textLabel = _initializer5$8 && _initializer5$8();
          this._placeholderLabel = _initializer6$5 && _initializer6$5();
          this._returnType = _initializer7$5 && _initializer7$5();
          this._string = _initializer8$5 && _initializer8$5();
          this._tabIndex = _initializer9$5 && _initializer9$5();
          this._backgroundImage = _initializer10$5 && _initializer10$5();
          this._inputFlag = _initializer11$5 && _initializer11$5();
          this._inputMode = _initializer12$4 && _initializer12$4();
          this._maxLength = _initializer13$2 && _initializer13$2();
          this._isLabelVisible = false;
        }
        __preload() {
          this._init();
        }
        onEnable() {
          {
            this._registerEvent();
          }
          this._ensureBackgroundSprite();
          if (this._impl) {
            this._impl.onEnable();
          }
        }
        _beforeDraw() {
          if (this._impl) {
            this._impl.beforeDraw();
          }
        }
        onDisable() {
          {
            this._unregisterEvent();
          }
          this._unregisterBackgroundEvent();
          if (this._impl) {
            this._impl.onDisable();
          }
        }
        onDestroy() {
          director.off("director_before_draw", this._beforeDraw, this);
          if (this._impl) {
            this._impl.clear();
          }
        }
        setFocus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        }
        focus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        }
        blur() {
          if (this._impl) {
            this._impl.setFocus(false);
          }
        }
        isFocused() {
          if (this._impl) {
            return this._impl.isFocused();
          }
          return false;
        }
        _editBoxEditingDidBegan() {
          EventHandler.emitEvents(this.editingDidBegan, this);
          this.node.emit("editing-did-began", this);
        }
        _editBoxEditingDidEnded(text) {
          EventHandler.emitEvents(this.editingDidEnded, this);
          this.node.emit("editing-did-ended", this, text);
        }
        _editBoxTextChanged(text) {
          text = this._updateLabelStringStyle(text, true);
          this.string = text;
          EventHandler.emitEvents(this.textChanged, text, this);
          this.node.emit("text-changed", this);
        }
        _editBoxEditingReturn(text) {
          EventHandler.emitEvents(this.editingReturn, this);
          this.node.emit("editing-return", this, text);
        }
        _showLabels() {
          this._isLabelVisible = true;
          this._updateLabels();
        }
        _hideLabels() {
          this._isLabelVisible = false;
          if (this._textLabel) {
            this._textLabel.node.active = false;
          }
          if (this._placeholderLabel) {
            this._placeholderLabel.node.active = false;
          }
        }
        _onTouchBegan(event) {
          event.propagationStopped = true;
        }
        _onTouchCancel(event) {
          event.propagationStopped = true;
        }
        _onTouchEnded(event) {
          if (this._impl) {
            this._impl.beginEditing();
          }
          event.propagationStopped = true;
        }
        _init() {
          this._updatePlaceholderLabel();
          this._updateTextLabel();
          this._isLabelVisible = true;
          this.node.on("size-changed", this._resizeChildNodes, this);
          director.on("director_before_draw", this._beforeDraw, this);
          const impl = this._impl = new EditBox._EditBoxImpl();
          impl.init(this);
          this._updateString(this._string);
          this._syncSize();
        }
        _ensureBackgroundSprite() {
          if (!this._background) {
            let 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();
            }
          }
        }
        _updateTextLabel() {
          let textLabel = this._textLabel;
          if (!textLabel) {
            let 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 === 0) {
            textLabel.verticalAlign = 0;
            textLabel.enableWrapText = true;
          } else {
            textLabel.enableWrapText = false;
          }
          textLabel.string = this._updateLabelStringStyle(this._string);
        }
        _updatePlaceholderLabel() {
          let placeholderLabel = this._placeholderLabel;
          if (!placeholderLabel) {
            let 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 === 0) {
            placeholderLabel.enableWrapText = true;
          } else {
            placeholderLabel.enableWrapText = false;
          }
          placeholderLabel.string = this.placeholder;
        }
        _syncSize() {
          const trans = this.node._uiProps.uiTransformComp;
          const size = trans.contentSize;
          if (this._background) {
            const 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);
          }
        }
        _updateLabels() {
          if (this._isLabelVisible) {
            const content = this._string;
            if (this._textLabel) {
              this._textLabel.node.active = content !== '';
            }
            if (this._placeholderLabel) {
              this._placeholderLabel.node.active = content === '';
            }
          }
        }
        _updateString(text) {
          const textLabel = this._textLabel;
          if (!textLabel) {
            return;
          }
          let displayText = text;
          if (displayText) {
            displayText = this._updateLabelStringStyle(displayText);
          }
          textLabel.string = displayText;
          this._updateLabels();
        }
        _updateLabelStringStyle(text, ignorePassword = false) {
          const inputFlag = this._inputFlag;
          if (!ignorePassword && inputFlag === 0) {
            let passwordString = '';
            const len = text.length;
            for (let i = 0; i < len; ++i) {
              passwordString += '\u25CF';
            }
            text = passwordString;
          } else if (inputFlag === 4) {
            text = text.toUpperCase();
          } else if (inputFlag === 2) {
            text = capitalize(text);
          } else if (inputFlag === 3) {
            text = capitalizeFirstLetter(text);
          }
          return text;
        }
        _registerEvent() {
          this.node.on("touch-start", this._onTouchBegan, this);
          this.node.on("touch-end", this._onTouchEnded, this);
          this.node.on("xrui-unclick", this._xrUnClick, this);
          this.node.on("xr-keyboard-input", this._xrKeyBoardInput, this);
        }
        _unregisterEvent() {
          this.node.off("touch-start", this._onTouchBegan, this);
          this.node.off("touch-end", this._onTouchEnded, this);
          this.node.off("xrui-unclick", this._xrUnClick, this);
          this.node.off("xr-keyboard-input", this._xrKeyBoardInput, this);
        }
        _onBackgroundSpriteFrameChanged() {
          if (!this._background) {
            return;
          }
          this.backgroundImage = this._background.spriteFrame;
        }
        _registerBackgroundEvent() {
          const node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.on("spriteframe-changed", this._onBackgroundSpriteFrameChanged, this);
        }
        _unregisterBackgroundEvent() {
          const node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.off("spriteframe-changed", this._onBackgroundSpriteFrameChanged, this);
        }
        _updateLabelPosition(size) {
          const trans = this.node._uiProps.uiTransformComp;
          const offX = -trans.anchorX * trans.width;
          const offY = -trans.anchorY * trans.height;
          const placeholderLabel = this._placeholderLabel;
          const 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 === 0) {
              textLabel.verticalAlign = 0;
            }
            textLabel.enableWrapText = this._inputMode === 0;
          }
          if (placeholderLabel) {
            placeholderLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING, size.height);
            placeholderLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, placeholderLabel.node.position.z);
            placeholderLabel.enableWrapText = this._inputMode === 0;
          }
        }
        _resizeChildNodes() {
          const trans = this.node._uiProps.uiTransformComp;
          const 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);
          }
          const 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);
          }
          const backgroundNode = this._background && this._background.node;
          if (backgroundNode) {
            backgroundNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          this._syncSize();
        }
        _xrUnClick() {
          this.node.emit("xr-editing-did-began", this._maxLength, this.string);
        }
        _xrKeyBoardInput(str) {
          this.string = str;
        }
      }, _class3$b._EditBoxImpl = EditBoxImplBase, _class3$b.KeyboardReturnType = KeyboardReturnType, _class3$b.InputFlag = InputFlag, _class3$b.InputMode = InputMode, _class3$b.EventType = EditBoxEventType, _class3$b), (_applyDecoratedDescriptor(_class2$g.prototype, "textLabel", [_dec4$b], Object.getOwnPropertyDescriptor(_class2$g.prototype, "textLabel"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "placeholderLabel", [_dec5$b], Object.getOwnPropertyDescriptor(_class2$g.prototype, "placeholderLabel"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "backgroundImage", [_dec6$5], Object.getOwnPropertyDescriptor(_class2$g.prototype, "backgroundImage"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "inputFlag", [_dec7$3], Object.getOwnPropertyDescriptor(_class2$g.prototype, "inputFlag"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "inputMode", [_dec8$2], Object.getOwnPropertyDescriptor(_class2$g.prototype, "inputMode"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "returnType", [_dec9$2], Object.getOwnPropertyDescriptor(_class2$g.prototype, "returnType"), _class2$g.prototype), _initializer$g = applyDecoratedInitializer(_class2$g.prototype, "editingDidBegan", [_dec10, serializable$l], function () {
        return [];
      }), _initializer2$e = applyDecoratedInitializer(_class2$g.prototype, "textChanged", [_dec11, serializable$l], function () {
        return [];
      }), _initializer3$b = applyDecoratedInitializer(_class2$g.prototype, "editingDidEnded", [_dec12, serializable$l], function () {
        return [];
      }), _initializer4$a = applyDecoratedInitializer(_class2$g.prototype, "editingReturn", [_dec13, serializable$l], function () {
        return [];
      }), _initializer5$8 = applyDecoratedInitializer(_class2$g.prototype, "_textLabel", [serializable$l], function () {
        return null;
      }), _initializer6$5 = applyDecoratedInitializer(_class2$g.prototype, "_placeholderLabel", [serializable$l], function () {
        return null;
      }), _initializer7$5 = applyDecoratedInitializer(_class2$g.prototype, "_returnType", [serializable$l], function () {
        return 0;
      }), _initializer8$5 = applyDecoratedInitializer(_class2$g.prototype, "_string", [serializable$l], function () {
        return '';
      }), _initializer9$5 = applyDecoratedInitializer(_class2$g.prototype, "_tabIndex", [serializable$l], function () {
        return 0;
      }), _initializer10$5 = applyDecoratedInitializer(_class2$g.prototype, "_backgroundImage", [serializable$l], function () {
        return null;
      }), _initializer11$5 = applyDecoratedInitializer(_class2$g.prototype, "_inputFlag", [serializable$l], function () {
        return 5;
      }), _initializer12$4 = applyDecoratedInitializer(_class2$g.prototype, "_inputMode", [serializable$l], function () {
        return 0;
      }), _initializer13$2 = applyDecoratedInitializer(_class2$g.prototype, "_maxLength", [serializable$l], function () {
        return 20;
      })), _class2$g)) || _class$j) || _class$j) || _class$j); exports({ EditBox: EditBox, EditBoxComponent: EditBox });
      if (typeof window === 'object' && typeof document === 'object' && !MINIGAME && !JSB && !RUNTIME_BASED) {
        EditBox._EditBoxImpl = EditBoxImpl;
      }
      legacyCC.internal.EditBox = EditBox;

      var _dec$i, _dec2$f, _dec3$e, _dec4$a, _dec5$a, _dec6$4, _dec7$2, _dec8$1, _dec9$1, _class$i, _class2$f, _initializer$f, _initializer2$d, _initializer3$a, _initializer4$9, _initializer5$7, _initializer6$4, _initializer7$4, _initializer8$4, _initializer9$4, _initializer10$4, _initializer11$4, _initializer12$3, _initializer13$1, _initializer14$1, _initializer15$1, _initializer16$1, _class3$a;
      const LayoutType = {
        "NONE": 0,
        "HORIZONTAL": 1,
        "VERTICAL": 2,
        "GRID": 3
      };
      ccenum(LayoutType);
      const LayoutResizeMode = {
        "NONE": 0,
        "CONTAINER": 1,
        "CHILDREN": 2
      };
      ccenum(LayoutResizeMode);
      const LayoutAxisDirection = {
        "HORIZONTAL": 0,
        "VERTICAL": 1
      };
      ccenum(LayoutAxisDirection);
      const LayoutVerticalDirection = {
        "BOTTOM_TO_TOP": 0,
        "TOP_TO_BOTTOM": 1
      };
      ccenum(LayoutVerticalDirection);
      const LayoutHorizontalDirection = {
        "LEFT_TO_RIGHT": 0,
        "RIGHT_TO_LEFT": 1
      };
      ccenum(LayoutHorizontalDirection);
      const LayoutConstraint = {
        "NONE": 0,
        "FIXED_ROW": 1,
        "FIXED_COL": 2
      };
      ccenum(LayoutConstraint);
      const _tempVec3$2 = new Vec3();
      let Layout = (_dec$i = ccclass$H('cc.Layout'), _dec2$f = executionOrder$1(110), _dec3$e = requireComponent(UITransform), _dec4$a = type$a(LayoutType), _dec5$a = type$a(LayoutResizeMode), _dec6$4 = type$a(LayoutAxisDirection), _dec7$2 = type$a(LayoutVerticalDirection), _dec8$1 = type$a(LayoutHorizontalDirection), _dec9$1 = type$a(LayoutConstraint), _dec$i(_class$i = _dec2$f(_class$i = _dec3$e(_class$i = (_class2$f = (_class3$a = class Layout extends Component {
        constructor() {
          super();
          this._resizeMode = _initializer$f && _initializer$f();
          this._layoutType = _initializer2$d && _initializer2$d();
          this._cellSize = _initializer3$a && _initializer3$a();
          this._startAxis = _initializer4$9 && _initializer4$9();
          this._paddingLeft = _initializer5$7 && _initializer5$7();
          this._paddingRight = _initializer6$4 && _initializer6$4();
          this._paddingTop = _initializer7$4 && _initializer7$4();
          this._paddingBottom = _initializer8$4 && _initializer8$4();
          this._spacingX = _initializer9$4 && _initializer9$4();
          this._spacingY = _initializer10$4 && _initializer10$4();
          this._verticalDirection = _initializer11$4 && _initializer11$4();
          this._horizontalDirection = _initializer12$3 && _initializer12$3();
          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;
        }
        get alignHorizontal() {
          return this._isAlign;
        }
        set alignHorizontal(value) {
          if (this._layoutType !== 1) {
            return;
          }
          this._isAlign = value;
          this._doLayoutDirty();
        }
        get alignVertical() {
          return this._isAlign;
        }
        set alignVertical(value) {
          if (this._layoutType !== 2) {
            return;
          }
          this._isAlign = value;
          this._doLayoutDirty();
        }
        get type() {
          return this._layoutType;
        }
        set type(value) {
          this._layoutType = value;
          this._doLayoutDirty();
        }
        get resizeMode() {
          return this._resizeMode;
        }
        set resizeMode(value) {
          if (this._layoutType === 0) {
            return;
          }
          this._resizeMode = value;
          this._doLayoutDirty();
        }
        get cellSize() {
          return this._cellSize;
        }
        set cellSize(value) {
          if (this._cellSize === value) {
            return;
          }
          this._cellSize.set(value);
          this._doLayoutDirty();
        }
        get startAxis() {
          return this._startAxis;
        }
        set startAxis(value) {
          if (this._startAxis === value) {
            return;
          }
          this._startAxis = value;
          this._doLayoutDirty();
        }
        get paddingLeft() {
          return this._paddingLeft;
        }
        set paddingLeft(value) {
          if (this._paddingLeft === value) {
            return;
          }
          this._paddingLeft = value;
          this._doLayoutDirty();
        }
        get paddingRight() {
          return this._paddingRight;
        }
        set paddingRight(value) {
          if (this._paddingRight === value) {
            return;
          }
          this._paddingRight = value;
          this._doLayoutDirty();
        }
        get paddingTop() {
          return this._paddingTop;
        }
        set paddingTop(value) {
          if (this._paddingTop === value) {
            return;
          }
          this._paddingTop = value;
          this._doLayoutDirty();
        }
        get paddingBottom() {
          return this._paddingBottom;
        }
        set paddingBottom(value) {
          if (this._paddingBottom === value) {
            return;
          }
          this._paddingBottom = value;
          this._doLayoutDirty();
        }
        get spacingX() {
          return this._spacingX;
        }
        set spacingX(value) {
          if (this._spacingX === value) {
            return;
          }
          this._spacingX = value;
          this._doLayoutDirty();
        }
        get spacingY() {
          return this._spacingY;
        }
        set spacingY(value) {
          if (this._spacingY === value) {
            return;
          }
          this._spacingY = value;
          this._doLayoutDirty();
        }
        get verticalDirection() {
          return this._verticalDirection;
        }
        set verticalDirection(value) {
          if (this._verticalDirection === value) {
            return;
          }
          this._verticalDirection = value;
          this._doLayoutDirty();
        }
        get horizontalDirection() {
          return this._horizontalDirection;
        }
        set horizontalDirection(value) {
          if (this._horizontalDirection === value) {
            return;
          }
          this._horizontalDirection = value;
          this._doLayoutDirty();
        }
        get padding() {
          return this._paddingLeft;
        }
        set padding(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();
          }
        }
        get constraint() {
          return this._constraint;
        }
        set constraint(value) {
          if (this._layoutType === 0 || this._constraint === value) {
            return;
          }
          this._constraint = value;
          this._doLayoutDirty();
        }
        get constraintNum() {
          return this._constraintNum;
        }
        set constraintNum(value) {
          if (this._constraint === 0 || this._constraintNum === value) {
            return;
          }
          if (value <= 0) {
            warnID(16400);
          }
          this._constraintNum = value;
          this._doLayoutDirty();
        }
        get affectedByScale() {
          return this._affectedByScale;
        }
        set affectedByScale(value) {
          this._affectedByScale = value;
          this._doLayoutDirty();
        }
        updateLayout(force = false) {
          if (this._layoutDirty || force) {
            this._doLayout();
            this._layoutDirty = false;
          }
        }
        onEnable() {
          this._addEventListeners();
          const trans = this.node._uiProps.uiTransformComp;
          if (trans.contentSize.equals(Size$1.ZERO)) {
            trans.setContentSize(this._layoutSize);
          }
          this._childrenChanged();
        }
        onDisable() {
          this._usefulLayoutObj.length = 0;
          this._removeEventListeners();
        }
        _checkUsefulObj() {
          this._usefulLayoutObj.length = 0;
          const children = this.node.children;
          for (let i = 0; i < children.length; ++i) {
            const child = children[i];
            const uiTrans = child._uiProps.uiTransformComp;
            if (child.activeInHierarchy && uiTrans) {
              this._usefulLayoutObj.push(uiTrans);
            }
          }
        }
        _addEventListeners() {
          director.on("director_after_update", this.updateLayout, this);
          this.node.on("size-changed", this._resized, this);
          this.node.on("anchor-changed", this._doLayoutDirty, this);
          this.node.on("child-added", this._childAdded, this);
          this.node.on("child-removed", this._childRemoved, this);
          this.node.on("sibling-order-changed", this._childrenChanged, this);
          this.node.on('childrenSiblingOrderChanged', this.updateLayout, this);
          this._addChildrenEventListeners();
        }
        _removeEventListeners() {
          director.off("director_after_update", this.updateLayout, this);
          this.node.off("size-changed", this._resized, this);
          this.node.off("anchor-changed", this._doLayoutDirty, this);
          this.node.off("child-added", this._childAdded, this);
          this.node.off("child-removed", this._childRemoved, this);
          this.node.off("sibling-order-changed", this._childrenChanged, this);
          this.node.off('childrenSiblingOrderChanged', this.updateLayout, this);
          this._removeChildrenEventListeners();
        }
        _addChildrenEventListeners() {
          const children = this.node.children;
          for (let i = 0; i < children.length; ++i) {
            const child = children[i];
            child.on("size-changed", this._doLayoutDirty, this);
            child.on("transform-changed", this._transformDirty, this);
            child.on("anchor-changed", this._doLayoutDirty, this);
            child.on("active-in-hierarchy-changed", this._childrenChanged, this);
          }
        }
        _removeChildrenEventListeners() {
          const children = this.node.children;
          for (let i = 0; i < children.length; ++i) {
            const child = children[i];
            child.off("size-changed", this._doLayoutDirty, this);
            child.off("transform-changed", this._transformDirty, this);
            child.off("anchor-changed", this._doLayoutDirty, this);
            child.off("active-in-hierarchy-changed", this._childrenChanged, this);
          }
        }
        _childAdded(child) {
          child.on("size-changed", this._doLayoutDirty, this);
          child.on("transform-changed", this._transformDirty, this);
          child.on("anchor-changed", this._doLayoutDirty, this);
          child.on("active-in-hierarchy-changed", this._childrenChanged, this);
          this._childrenChanged();
        }
        _childRemoved(child) {
          child.off("size-changed", this._doLayoutDirty, this);
          child.off("transform-changed", this._transformDirty, this);
          child.off("anchor-changed", this._doLayoutDirty, this);
          child.off("active-in-hierarchy-changed", this._childrenChanged, this);
          this._childrenChanged();
        }
        _resized() {
          this._layoutSize.set(this.node._uiProps.uiTransformComp.contentSize);
          this._doLayoutDirty();
        }
        _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) {
          const trans = this.node._uiProps.uiTransformComp;
          const layoutAnchor = trans.anchorPoint;
          const limit = this._getFixedBreakingNum();
          let sign = 1;
          let paddingX = this._paddingLeft;
          if (this._horizontalDirection === 1) {
            sign = -1;
            paddingX = this._paddingRight;
          }
          const startPos = (this._horizontalDirection - layoutAnchor.x) * baseWidth + sign * paddingX;
          let nextX = startPos - sign * this._spacingX;
          let totalHeight = 0;
          let rowMaxHeight = 0;
          let tempMaxHeight = 0;
          let maxHeight = 0;
          let isBreak = false;
          const activeChildCount = this._usefulLayoutObj.length;
          let newChildWidth = this._cellSize.width;
          const paddingH = this._getPaddingH();
          if (this._layoutType !== 3 && this._resizeMode === 2) {
            newChildWidth = (baseWidth - paddingH - (activeChildCount - 1) * this._spacingX) / activeChildCount;
          }
          const children = this._usefulLayoutObj;
          for (let i = 0; i < children.length; ++i) {
            const childTrans = children[i];
            const child = childTrans.node;
            const scale = child.scale;
            const childScaleX = this._getUsedScaleValue(scale.x);
            const childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === 2) {
              childTrans.width = newChildWidth / childScaleX;
              if (this._layoutType === 3) {
                childTrans.height = this._cellSize.height / childScaleY;
              }
            }
            const anchorX = Math.abs(this._horizontalDirection - childTrans.anchorX);
            const childBoundingBoxWidth = childTrans.width * childScaleX;
            const childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxHeight > tempMaxHeight) {
              maxHeight = Math.max(tempMaxHeight, maxHeight);
              rowMaxHeight = tempMaxHeight || childBoundingBoxHeight;
              tempMaxHeight = childBoundingBoxHeight;
            }
            nextX += sign * (anchorX * childBoundingBoxWidth + this._spacingX);
            const 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 {
                const boundary = (1 - this._horizontalDirection - layoutAnchor.x) * baseWidth;
                const 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;
              }
            }
            const finalPositionY = fnPositionY(child, childTrans, totalHeight);
            if (applyChildren) {
              child.setPosition(nextX, finalPositionY);
            }
            nextX += rightBoundaryOfChild;
          }
          rowMaxHeight = Math.max(rowMaxHeight, tempMaxHeight);
          const containerResizeBoundary = Math.max(maxHeight, totalHeight + rowMaxHeight) + this._getPaddingV();
          return containerResizeBoundary;
        }
        _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) {
          const trans = this.node._uiProps.uiTransformComp;
          const layoutAnchor = trans.anchorPoint;
          const limit = this._getFixedBreakingNum();
          let sign = 1;
          let paddingY = this._paddingBottom;
          if (this._verticalDirection === 1) {
            sign = -1;
            paddingY = this._paddingTop;
          }
          const startPos = (this._verticalDirection - layoutAnchor.y) * baseHeight + sign * paddingY;
          let nextY = startPos - sign * this._spacingY;
          let tempMaxWidth = 0;
          let maxWidth = 0;
          let colMaxWidth = 0;
          let totalWidth = 0;
          let isBreak = false;
          const activeChildCount = this._usefulLayoutObj.length;
          let newChildHeight = this._cellSize.height;
          const paddingV = this._getPaddingV();
          if (this._layoutType !== 3 && this._resizeMode === 2) {
            newChildHeight = (baseHeight - paddingV - (activeChildCount - 1) * this._spacingY) / activeChildCount;
          }
          const children = this._usefulLayoutObj;
          for (let i = 0; i < children.length; ++i) {
            const childTrans = children[i];
            const child = childTrans.node;
            const scale = child.scale;
            const childScaleX = this._getUsedScaleValue(scale.x);
            const childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === 2) {
              childTrans.height = newChildHeight / childScaleY;
              if (this._layoutType === 3) {
                childTrans.width = this._cellSize.width / childScaleX;
              }
            }
            const anchorY = Math.abs(this._verticalDirection - childTrans.anchorY);
            const childBoundingBoxWidth = childTrans.width * childScaleX;
            const childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxWidth > tempMaxWidth) {
              maxWidth = Math.max(tempMaxWidth, maxWidth);
              colMaxWidth = tempMaxWidth || childBoundingBoxWidth;
              tempMaxWidth = childBoundingBoxWidth;
            }
            nextY += sign * (anchorY * childBoundingBoxHeight + this._spacingY);
            const 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 {
                const boundary = (1 - this._verticalDirection - layoutAnchor.y) * baseHeight;
                const 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;
              }
            }
            const 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);
          const containerResizeBoundary = Math.max(maxWidth, totalWidth + colMaxWidth) + this._getPaddingH();
          return containerResizeBoundary;
        }
        _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) {
          const baseWidth = layoutSize.width;
          let sign = 1;
          let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
          let paddingY = this._paddingBottom;
          if (this._verticalDirection === 1) {
            sign = -1;
            bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height;
            paddingY = this._paddingTop;
          }
          const fnPositionY = (child, childTrans, topOffset) => bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * this._getUsedScaleValue(child.scale.y) + paddingY);
          let newHeight = 0;
          if (this._resizeMode === 1) {
            newHeight = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
            bottomBoundaryOfLayout = -layoutAnchor.y * newHeight;
            if (this._verticalDirection === 1) {
              sign = -1;
              bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight;
            }
          }
          this._doLayoutHorizontally(baseWidth, true, fnPositionY, true);
          if (this._resizeMode === 1) {
            this.node._uiProps.uiTransformComp.setContentSize(baseWidth, newHeight);
          }
        }
        _doLayoutGridAxisVertical(layoutAnchor, layoutSize) {
          const baseHeight = layoutSize.height;
          let sign = 1;
          let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
          let paddingX = this._paddingLeft;
          if (this._horizontalDirection === 1) {
            sign = -1;
            leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width;
            paddingX = this._paddingRight;
          }
          const fnPositionX = (child, childTrans, leftOffset) => leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * this._getUsedScaleValue(child.scale.x) + paddingX);
          let newWidth = 0;
          if (this._resizeMode === 1) {
            newWidth = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
            leftBoundaryOfLayout = -layoutAnchor.x * newWidth;
            if (this._horizontalDirection === 1) {
              sign = -1;
              leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth;
            }
          }
          this._doLayoutVertically(baseHeight, true, fnPositionX, true);
          if (this._resizeMode === 1) {
            this.node._uiProps.uiTransformComp.setContentSize(newWidth, baseHeight);
          }
        }
        _doLayoutGrid() {
          const trans = this.node._uiProps.uiTransformComp;
          const layoutAnchor = trans.anchorPoint;
          const layoutSize = trans.contentSize;
          if (this.startAxis === 0) {
            this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize);
          } else if (this.startAxis === 1) {
            this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
          }
        }
        _getHorizontalBaseWidth(horizontal = true) {
          const children = this._usefulLayoutObj;
          let baseSize = 0;
          const activeChildCount = children.length;
          if (this._resizeMode === 1) {
            for (let i = 0; i < children.length; ++i) {
              const childTrans = children[i];
              const child = childTrans.node;
              const 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;
        }
        _getVerticalBaseHeight() {
          const children = this._usefulLayoutObj;
          let baseSize = 0;
          const activeChildCount = children.length;
          if (this._resizeMode === 1) {
            for (let i = 0; i < children.length; ++i) {
              const childTrans = children[i];
              const child = childTrans.node;
              const 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;
        }
        _doLayout() {
          if (!this._init || this._childrenDirty) {
            this._checkUsefulObj();
            this._init = true;
            this._childrenDirty = false;
          }
          if (this._layoutType === 1) {
            const newWidth = this._getHorizontalBaseWidth();
            const fnPositionY = child => {
              const pos = this._isAlign ? Vec3.ZERO : child.position;
              return pos.y;
            };
            this._doLayoutHorizontally(newWidth, false, fnPositionY, true);
            this.node._uiProps.uiTransformComp.width = newWidth;
          } else if (this._layoutType === 2) {
            const newHeight = this._getVerticalBaseHeight();
            const fnPositionX = child => {
              const pos = this._isAlign ? Vec3.ZERO : child.position;
              return pos.x;
            };
            this._doLayoutVertically(newHeight, false, fnPositionX, true);
            this.node._uiProps.uiTransformComp.height = newHeight;
          } else if (this._layoutType === 3) {
            this._doLayoutGrid();
          }
        }
        _getUsedScaleValue(value) {
          return this._affectedByScale ? Math.abs(value) : 1;
        }
        _transformDirty(type) {
          if (!(type & 4) || !(type & 1) || !this._affectedByScale) {
            return;
          }
          this._doLayoutDirty();
        }
        _doLayoutDirty() {
          this._layoutDirty = true;
        }
        _childrenChanged() {
          this._childrenDirty = true;
          this._doLayoutDirty();
        }
        _getPaddingH() {
          return this._paddingLeft + this._paddingRight;
        }
        _getPaddingV() {
          return this._paddingTop + this._paddingBottom;
        }
        _getFixedBreakingNum() {
          if (this._layoutType !== 3 || this._constraint === 0 || this._constraintNum <= 0) {
            return 0;
          }
          let num = this._constraint === 1 ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          if (this._startAxis === 1) {
            num = this._constraint === 2 ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          }
          return num;
        }
      }, _class3$a.Type = LayoutType, _class3$a.VerticalDirection = LayoutVerticalDirection, _class3$a.HorizontalDirection = LayoutHorizontalDirection, _class3$a.ResizeMode = LayoutResizeMode, _class3$a.AxisDirection = LayoutAxisDirection, _class3$a.Constraint = LayoutConstraint, _class3$a), (_applyDecoratedDescriptor(_class2$f.prototype, "type", [_dec4$a], Object.getOwnPropertyDescriptor(_class2$f.prototype, "type"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "resizeMode", [_dec5$a], Object.getOwnPropertyDescriptor(_class2$f.prototype, "resizeMode"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "startAxis", [_dec6$4], Object.getOwnPropertyDescriptor(_class2$f.prototype, "startAxis"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "verticalDirection", [_dec7$2], Object.getOwnPropertyDescriptor(_class2$f.prototype, "verticalDirection"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "horizontalDirection", [_dec8$1], Object.getOwnPropertyDescriptor(_class2$f.prototype, "horizontalDirection"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "constraint", [_dec9$1], Object.getOwnPropertyDescriptor(_class2$f.prototype, "constraint"), _class2$f.prototype), _initializer$f = applyDecoratedInitializer(_class2$f.prototype, "_resizeMode", [serializable$l], function () {
        return 0;
      }), _initializer2$d = applyDecoratedInitializer(_class2$f.prototype, "_layoutType", [serializable$l], function () {
        return 0;
      }), _initializer3$a = applyDecoratedInitializer(_class2$f.prototype, "_cellSize", [serializable$l], function () {
        return new Size$1(40, 40);
      }), _initializer4$9 = applyDecoratedInitializer(_class2$f.prototype, "_startAxis", [serializable$l], function () {
        return 0;
      }), _initializer5$7 = applyDecoratedInitializer(_class2$f.prototype, "_paddingLeft", [serializable$l], function () {
        return 0;
      }), _initializer6$4 = applyDecoratedInitializer(_class2$f.prototype, "_paddingRight", [serializable$l], function () {
        return 0;
      }), _initializer7$4 = applyDecoratedInitializer(_class2$f.prototype, "_paddingTop", [serializable$l], function () {
        return 0;
      }), _initializer8$4 = applyDecoratedInitializer(_class2$f.prototype, "_paddingBottom", [serializable$l], function () {
        return 0;
      }), _initializer9$4 = applyDecoratedInitializer(_class2$f.prototype, "_spacingX", [serializable$l], function () {
        return 0;
      }), _initializer10$4 = applyDecoratedInitializer(_class2$f.prototype, "_spacingY", [serializable$l], function () {
        return 0;
      }), _initializer11$4 = applyDecoratedInitializer(_class2$f.prototype, "_verticalDirection", [serializable$l], function () {
        return 1;
      }), _initializer12$3 = applyDecoratedInitializer(_class2$f.prototype, "_horizontalDirection", [serializable$l], function () {
        return 0;
      }), _initializer13$1 = applyDecoratedInitializer(_class2$f.prototype, "_constraint", [serializable$l], function () {
        return 0;
      }), _initializer14$1 = applyDecoratedInitializer(_class2$f.prototype, "_constraintNum", [serializable$l], function () {
        return 2;
      }), _initializer15$1 = applyDecoratedInitializer(_class2$f.prototype, "_affectedByScale", [serializable$l], function () {
        return false;
      }), _initializer16$1 = applyDecoratedInitializer(_class2$f.prototype, "_isAlign", [serializable$l], function () {
        return false;
      })), _class2$f)) || _class$i) || _class$i) || _class$i); exports({ Layout: Layout, LayoutComponent: Layout });
      legacyCC.Layout = Layout;

      var _dec$h, _dec2$e, _dec3$d, _dec4$9, _dec5$9, _class$h, _class2$e, _initializer$e, _initializer2$c, _initializer3$9, _initializer4$8, _initializer5$6, _class3$9;
      const Mode = {
        "HORIZONTAL": 0,
        "VERTICAL": 1,
        "FILLED": 2
      };
      Enum(Mode);
      let ProgressBar = (_dec$h = ccclass$H('cc.ProgressBar'), _dec2$e = executionOrder$1(110), _dec3$d = requireComponent(UITransform), _dec4$9 = type$a(Sprite), _dec5$9 = type$a(Mode), _dec$h(_class$h = _dec2$e(_class$h = _dec3$d(_class$h = (_class2$e = (_class3$9 = class ProgressBar extends Component {
        constructor() {
          super();
          this._barSprite = _initializer$e && _initializer$e();
          this._mode = _initializer2$c && _initializer2$c();
          this._totalLength = _initializer3$9 && _initializer3$9();
          this._progress = _initializer4$8 && _initializer4$8();
          this._reverse = _initializer5$6 && _initializer5$6();
        }
        get barSprite() {
          return this._barSprite;
        }
        set barSprite(value) {
          if (this._barSprite === value) {
            return;
          }
          this._barSprite = value;
          this._initBarSprite();
        }
        get mode() {
          return this._mode;
        }
        set mode(value) {
          if (this._mode === value) {
            return;
          }
          this._mode = value;
          if (this._barSprite) {
            const entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            const entitySize = entity._uiProps.uiTransformComp.contentSize;
            if (this._mode === 0) {
              this.totalLength = entitySize.width;
            } else if (this._mode === 1) {
              this.totalLength = entitySize.height;
            } else if (this._mode === 2) {
              this.totalLength = this._barSprite.fillRange;
            }
          }
        }
        get totalLength() {
          return this._totalLength;
        }
        set totalLength(value) {
          if (this._mode === 2) {
            value = clamp01(value);
          }
          if (this._totalLength === value) {
            return;
          }
          this._totalLength = value;
          this._updateBarStatus();
        }
        get progress() {
          return this._progress;
        }
        set progress(value) {
          if (this._progress === value) {
            return;
          }
          this._progress = value;
          this._updateBarStatus();
        }
        get reverse() {
          return this._reverse;
        }
        set reverse(value) {
          if (this._reverse === value) {
            return;
          }
          this._reverse = value;
          if (this._barSprite) {
            this._barSprite.fillStart = 1 - this._barSprite.fillStart;
          }
          this._updateBarStatus();
        }
        onLoad() {
          this._updateBarStatus();
        }
        _initBarSprite() {
          if (this._barSprite) {
            const entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            const trans = this.node._uiProps.uiTransformComp;
            const nodeSize = trans.contentSize;
            const nodeAnchor = trans.anchorPoint;
            const barSpriteSize = entity._uiProps.uiTransformComp.contentSize;
            if (this._barSprite.fillType === Sprite.FillType.RADIAL) {
              this._mode = 2;
            }
            if (this._mode === 0) {
              this.totalLength = barSpriteSize.width;
            } else if (this._mode === 1) {
              this.totalLength = barSpriteSize.height;
            } else {
              this.totalLength = this._barSprite.fillRange;
            }
            if (entity.parent === this.node) {
              const x = -nodeSize.width * nodeAnchor.x;
              entity.setPosition(x, 0, 0);
            }
          }
        }
        _updateBarStatus() {
          if (this._barSprite) {
            const entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            const entTrans = entity._uiProps.uiTransformComp;
            const entityAnchorPoint = entTrans.anchorPoint;
            const entitySize = entTrans.contentSize;
            let anchorPoint = new Vec2(0, 0.5);
            const progress = clamp01(this._progress);
            let actualLenth = this._totalLength * progress;
            let finalContentSize = entitySize;
            let totalWidth = 0;
            let totalHeight = 0;
            switch (this._mode) {
              case 0:
                if (this._reverse) {
                  anchorPoint = new Vec2(1, 0.5);
                }
                finalContentSize = new Size$1(actualLenth, entitySize.height);
                totalWidth = this._totalLength;
                totalHeight = entitySize.height;
                break;
              case 1:
                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 === 2) {
              if (this._barSprite.type !== Sprite.Type.FILLED) {
                warnID(16397);
              } else {
                if (this._reverse) {
                  actualLenth *= -1;
                }
                this._barSprite.fillRange = actualLenth;
              }
            } else if (this._barSprite.type !== Sprite.Type.FILLED) {
              const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
              const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
              const finalPosition = new Vec3(entity.position);
              finalPosition.add3f(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY, 0);
              entity.setPosition(finalPosition);
              entTrans.setAnchorPoint(anchorPoint);
              entTrans.setContentSize(finalContentSize);
            } else {
              warnID(16398);
            }
          }
        }
      }, _class3$9.Mode = Mode, _class3$9), (_applyDecoratedDescriptor(_class2$e.prototype, "barSprite", [_dec4$9], Object.getOwnPropertyDescriptor(_class2$e.prototype, "barSprite"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "mode", [_dec5$9], Object.getOwnPropertyDescriptor(_class2$e.prototype, "mode"), _class2$e.prototype), _initializer$e = applyDecoratedInitializer(_class2$e.prototype, "_barSprite", [serializable$l], function () {
        return null;
      }), _initializer2$c = applyDecoratedInitializer(_class2$e.prototype, "_mode", [serializable$l], function () {
        return 0;
      }), _initializer3$9 = applyDecoratedInitializer(_class2$e.prototype, "_totalLength", [serializable$l], function () {
        return 1;
      }), _initializer4$8 = applyDecoratedInitializer(_class2$e.prototype, "_progress", [serializable$l], function () {
        return 0.1;
      }), _initializer5$6 = applyDecoratedInitializer(_class2$e.prototype, "_reverse", [serializable$l], function () {
        return false;
      })), _class2$e)) || _class$h) || _class$h) || _class$h); exports({ ProgressBar: ProgressBar, ProgressBarComponent: ProgressBar });
      legacyCC.ProgressBar = ProgressBar;

      var _dec$g, _dec2$d, _dec3$c, _dec4$8, _dec5$8, _class$g, _class2$d, _initializer$d, _initializer2$b, _initializer3$8, _initializer4$7, _initializer5$5, _class3$8;
      const GETTING_SHORTER_FACTOR = 20;
      const _tempPos_1 = new Vec3();
      const _tempPos_2 = new Vec3();
      const _tempVec3$1 = new Vec3();
      const defaultAnchor = new Vec2();
      const _tempColor = new Color$1();
      const _tempVec2$2 = new Vec2();
      const ScrollBarDirection = {
        "HORIZONTAL": 0,
        "VERTICAL": 1
      };
      ccenum(ScrollBarDirection);
      let ScrollBar = (_dec$g = ccclass$H('cc.ScrollBar'), _dec2$d = executionOrder$1(110), _dec3$c = requireComponent(UITransform), _dec4$8 = type$a(Sprite), _dec5$8 = type$a(ScrollBarDirection), _dec$g(_class$g = _dec2$d(_class$g = _dec3$c(_class$g = (_class2$d = (_class3$8 = class ScrollBar extends Component {
        constructor() {
          super();
          this._scrollView = _initializer$d && _initializer$d();
          this._handle = _initializer2$b && _initializer2$b();
          this._direction = _initializer3$8 && _initializer3$8();
          this._enableAutoHide = _initializer4$7 && _initializer4$7();
          this._autoHideTime = _initializer5$5 && _initializer5$5();
          this._touching = false;
          this._opacity = 255;
          this._autoHideRemainingTime = 0;
        }
        get handle() {
          return this._handle;
        }
        set handle(value) {
          if (this._handle === value) {
            return;
          }
          this._handle = value;
          this.onScroll(Vec2.ZERO);
        }
        get direction() {
          return this._direction;
        }
        set direction(value) {
          if (this._direction === value) {
            return;
          }
          this._direction = value;
          this.onScroll(Vec2.ZERO);
        }
        get enableAutoHide() {
          return this._enableAutoHide;
        }
        set enableAutoHide(value) {
          if (this._enableAutoHide === value) {
            return;
          }
          this._enableAutoHide = value;
          if (this._enableAutoHide) {
            this._setOpacity(0);
          }
        }
        get autoHideTime() {
          return this._autoHideTime;
        }
        set autoHideTime(value) {
          if (this._autoHideTime === value) {
            return;
          }
          this._autoHideTime = value;
        }
        hide() {
          this._autoHideRemainingTime = 0;
          this._setOpacity(0);
        }
        show() {
          this._autoHideRemainingTime = this._autoHideTime;
          this._opacity = 255;
          this._setOpacity(this._opacity);
        }
        onScroll(outOfBoundary) {
          if (!this._scrollView) {
            return;
          }
          const content = this._scrollView.content;
          if (!content) {
            return;
          }
          const contentSize = content._uiProps.uiTransformComp.contentSize;
          const scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
          const barSize = this.node._uiProps.uiTransformComp.contentSize;
          if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
            return;
          }
          if (this._enableAutoHide) {
            this._autoHideRemainingTime = this._autoHideTime;
            this._setOpacity(this._opacity);
          }
          let contentMeasure = 0;
          let scrollViewMeasure = 0;
          let outOfBoundaryValue = 0;
          let contentPosition = 0;
          let handleNodeMeasure = 0;
          const outOfContentPosition = _tempVec2$2;
          outOfContentPosition.set(0, 0);
          if (this._direction === 0) {
            contentMeasure = contentSize.width;
            scrollViewMeasure = scrollViewSize.width;
            handleNodeMeasure = barSize.width;
            outOfBoundaryValue = outOfBoundary.x;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.x;
          } else if (this._direction === 1) {
            contentMeasure = contentSize.height;
            scrollViewMeasure = scrollViewSize.height;
            handleNodeMeasure = barSize.height;
            outOfBoundaryValue = outOfBoundary.y;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.y;
          }
          const length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
          const position = _tempVec2$2;
          this._calculatePosition(position, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
          this._updateLength(length);
          this._updateHandlerPosition(position);
        }
        setScrollView(scrollView) {
          this._scrollView = scrollView;
        }
        onTouchBegan() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = true;
        }
        onTouchEnded() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = false;
          if (this._autoHideTime <= 0) {
            return;
          }
          if (this._scrollView) {
            const content = this._scrollView.content;
            if (content) {
              const contentSize = content._uiProps.uiTransformComp.contentSize;
              const scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
              if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
                return;
              }
            }
          }
          this._autoHideRemainingTime = this._autoHideTime;
        }
        onEnable() {
          const renderComp = this.node.getComponent(Sprite);
          if (renderComp) {
            this._opacity = renderComp.color.a;
          }
        }
        start() {
          if (this._enableAutoHide) {
            this._setOpacity(0);
          }
        }
        update(dt) {
          this._processAutoHide(dt);
        }
        _convertToScrollViewSpace(out, content) {
          const scrollTrans = this._scrollView && this._scrollView.node._uiProps.uiTransformComp;
          const 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);
            const scrollViewSpacePos = scrollTrans.convertToNodeSpaceAR(_tempPos_2);
            scrollViewSpacePos.x += scrollTrans.anchorX * scrollTrans.width;
            scrollViewSpacePos.y += scrollTrans.anchorY * scrollTrans.height;
            out.set(scrollViewSpacePos.x, scrollViewSpacePos.y);
          }
        }
        _setOpacity(opacity) {
          if (this._handle) {
            let 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;
            }
          }
        }
        _updateHandlerPosition(position) {
          if (this._handle) {
            const oldPosition = _tempVec3$1;
            this._fixupHandlerPosition(oldPosition);
            this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y, oldPosition.z);
          }
        }
        _fixupHandlerPosition(out) {
          const uiTrans = this.node._uiProps.uiTransformComp;
          const barSize = uiTrans.contentSize;
          const barAnchor = uiTrans.anchorPoint;
          const handleSize = this.handle.node._uiProps.uiTransformComp.contentSize;
          const handleParent = this.handle.node.parent;
          Vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0);
          const leftBottomWorldPosition = this.node._uiProps.uiTransformComp.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
          const fixupPosition = out;
          fixupPosition.set(0, 0, 0);
          handleParent._uiProps.uiTransformComp.convertToNodeSpaceAR(leftBottomWorldPosition, fixupPosition);
          if (this.direction === 0) {
            fixupPosition.set(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, fixupPosition.z);
          } else if (this.direction === 1) {
            fixupPosition.set(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, fixupPosition.z);
          }
          this.handle.node.setPosition(fixupPosition);
        }
        _conditionalDisableScrollBar(contentSize, scrollViewSize) {
          if (contentSize.width <= scrollViewSize.width && this._direction === 0) {
            return true;
          }
          if (contentSize.height <= scrollViewSize.height && this._direction === 1) {
            return true;
          }
          return false;
        }
        _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
          let denominatorValue = contentMeasure;
          if (outOfBoundary) {
            denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTING_SHORTER_FACTOR;
          }
          const lengthRation = scrollViewMeasure / denominatorValue;
          return handleNodeMeasure * lengthRation;
        }
        _calculatePosition(out, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
          let denominatorValue = contentMeasure - scrollViewMeasure;
          if (outOfBoundary) {
            denominatorValue += Math.abs(outOfBoundary);
          }
          let positionRatio = 0;
          if (denominatorValue) {
            positionRatio = contentPosition / denominatorValue;
            positionRatio = clamp01(positionRatio);
          }
          const position = (handleNodeMeasure - actualLenth) * positionRatio;
          if (this._direction === 1) {
            out.set(0, position);
          } else {
            out.set(position, 0);
          }
        }
        _updateLength(length) {
          if (this._handle) {
            const handleNode = this._handle.node;
            const handleTrans = handleNode._uiProps.uiTransformComp;
            const handleNodeSize = handleTrans.contentSize;
            const anchor = handleTrans.anchorPoint;
            if (anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y) {
              handleTrans.setAnchorPoint(defaultAnchor);
            }
            if (this._direction === 0) {
              handleTrans.setContentSize(length, handleNodeSize.height);
            } else {
              handleTrans.setContentSize(handleNodeSize.width, length);
            }
          }
        }
        _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);
            const opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
            this._setOpacity(opacity);
          }
        }
      }, _class3$8.Direction = ScrollBarDirection, _class3$8), (_applyDecoratedDescriptor(_class2$d.prototype, "handle", [_dec4$8], Object.getOwnPropertyDescriptor(_class2$d.prototype, "handle"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "direction", [_dec5$8], Object.getOwnPropertyDescriptor(_class2$d.prototype, "direction"), _class2$d.prototype), _initializer$d = applyDecoratedInitializer(_class2$d.prototype, "_scrollView", [serializable$l], function () {
        return null;
      }), _initializer2$b = applyDecoratedInitializer(_class2$d.prototype, "_handle", [serializable$l], function () {
        return null;
      }), _initializer3$8 = applyDecoratedInitializer(_class2$d.prototype, "_direction", [serializable$l], function () {
        return 0;
      }), _initializer4$7 = applyDecoratedInitializer(_class2$d.prototype, "_enableAutoHide", [serializable$l], function () {
        return false;
      }), _initializer5$5 = applyDecoratedInitializer(_class2$d.prototype, "_autoHideTime", [serializable$l], function () {
        return 1.0;
      })), _class2$d)) || _class$g) || _class$g) || _class$g); exports({ ScrollBar: ScrollBar, ScrollBarComponent: ScrollBar });
      legacyCC.ScrollBar = ScrollBar;

      var _dec$f, _dec2$c, _class$f;
      let ViewGroup = exports("ViewGroup", (_dec$f = ccclass$H('cc.ViewGroup'), _dec2$c = executionOrder$1(110), _dec$f(_class$f = _dec2$c(_class$f = class ViewGroup extends Component {}) || _class$f) || _class$f));
      legacyCC.ViewGroup = ViewGroup;

      var _dec$e, _dec2$b, _dec3$b, _dec4$7, _dec5$7, _dec6$3, _dec7$1, _class$e, _class2$c, _initializer$c, _initializer2$a, _initializer3$7, _initializer4$6, _initializer5$4, _initializer6$3, _initializer7$3, _initializer8$3, _initializer9$3, _initializer10$3, _initializer11$3, _class3$7;
      const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
      const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
      const EPSILON = 1e-4;
      const TOLERANCE = 1e4;
      const MOVEMENT_FACTOR = 0.7;
      const _tempVec3 = v3();
      const _tempVec3_1 = v3();
      const _tempVec2$1 = v2$1();
      const _tempVec2_1$1 = v2$1();
      const quintEaseOut = time => {
        time -= 1;
        return time * time * time * time * time + 1;
      };
      const getTimeInMilliseconds = () => {
        const currentTime = new Date();
        return currentTime.getMilliseconds();
      };
      const 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
      };
      const _moveDeltaOptions = {
        anchor: v2$1(),
        applyToHorizontal: false,
        applyToVertical: false
      };
      const assignMoveDeltaOption = (x, y, applyToHorizontal, applyToVertical) => {
        _moveDeltaOptions.anchor.set(x, y);
        _moveDeltaOptions.applyToHorizontal = applyToHorizontal;
        _moveDeltaOptions.applyToVertical = applyToVertical;
      };
      const ScrollViewEventType = {
        "NONE": "",
        "SCROLL_TO_TOP": "scroll-to-top",
        "SCROLL_TO_BOTTOM": "scroll-to-bottom",
        "SCROLL_TO_LEFT": "scroll-to-left",
        "SCROLL_TO_RIGHT": "scroll-to-right",
        "SCROLL_BEGAN": "scroll-began",
        "SCROLL_ENDED": "scroll-ended",
        "BOUNCE_TOP": "bounce-top",
        "BOUNCE_BOTTOM": "bounce-bottom",
        "BOUNCE_LEFT": "bounce-left",
        "BOUNCE_RIGHT": "bounce-right",
        "SCROLLING": "scrolling",
        "SCROLL_ENG_WITH_THRESHOLD": "scroll-ended-with-threshold",
        "TOUCH_UP": "touch-up"
      };
      let ScrollView = (_dec$e = ccclass$H('cc.ScrollView'), _dec2$b = executionOrder$1(110), _dec3$b = requireComponent(UITransform), _dec4$7 = type$a(Node$1), _dec5$7 = type$a(ScrollBar), _dec6$3 = type$a(ScrollBar), _dec7$1 = type$a([EventHandler]), _dec$e(_class$e = _dec2$b(_class$e = _dec3$b(_class$e = (_class2$c = (_class3$7 = class ScrollView extends ViewGroup {
        get content() {
          return this._content;
        }
        set content(value) {
          if (this._content === value) {
            return;
          }
          const viewTrans = value && value.parent && value.parent._uiProps.uiTransformComp;
          if (value && (!value || !viewTrans)) {
            logID(4302);
            return;
          }
          this._content = value;
          this._calculateBoundary();
        }
        get horizontalScrollBar() {
          const horizontalScrollBar = this._horizontalScrollBar;
          if (horizontalScrollBar && !horizontalScrollBar.isValid) {
            errorID(4303, 'horizontal', this.node.name);
          }
          return horizontalScrollBar;
        }
        set horizontalScrollBar(value) {
          if (this._horizontalScrollBar === value) {
            return;
          }
          this._horizontalScrollBar = value;
          if (this._horizontalScrollBar) {
            this._horizontalScrollBar.setScrollView(this);
            this._updateScrollBar(Vec2.ZERO);
          }
        }
        get verticalScrollBar() {
          const verticalScrollBar = this._verticalScrollBar;
          if (verticalScrollBar && !verticalScrollBar.isValid) {
            errorID(4303, 'vertical', this.node.name);
          }
          return verticalScrollBar;
        }
        set verticalScrollBar(value) {
          if (this._verticalScrollBar === value) {
            return;
          }
          this._verticalScrollBar = value;
          if (this._verticalScrollBar) {
            this._verticalScrollBar.setScrollView(this);
            this._updateScrollBar(Vec2.ZERO);
          }
        }
        get view() {
          const parent = this._content && this._content.parent;
          if (!parent) {
            return null;
          }
          return parent._uiProps.uiTransformComp;
        }
        constructor() {
          super();
          this.bounceDuration = _initializer$c && _initializer$c();
          this.brake = _initializer2$a && _initializer2$a();
          this.elastic = _initializer3$7 && _initializer3$7();
          this.inertia = _initializer4$6 && _initializer4$6();
          this.horizontal = _initializer5$4 && _initializer5$4();
          this.vertical = _initializer6$3 && _initializer6$3();
          this.cancelInnerEvents = _initializer7$3 && _initializer7$3();
          this.scrollEvents = _initializer8$3 && _initializer8$3();
          this._autoScrolling = false;
          this._scrolling = false;
          this._content = _initializer9$3 && _initializer9$3();
          this._horizontalScrollBar = _initializer10$3 && _initializer10$3();
          this._verticalScrollBar = _initializer11$3 && _initializer11$3();
          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._deltaAmount = new Vec3();
          this._hoverIn = 0;
        }
        scrollToBottom(timeInSecond, attenuated = true) {
          this._doScroll(0, 0, false, true, timeInSecond, attenuated);
        }
        scrollToTop(timeInSecond, attenuated = true) {
          this._doScroll(0, 1, false, true, timeInSecond, attenuated);
        }
        scrollToLeft(timeInSecond, attenuated = true) {
          this._doScroll(0, 0, true, false, timeInSecond, attenuated);
        }
        scrollToRight(timeInSecond, attenuated = true) {
          this._doScroll(1, 0, true, false, timeInSecond, attenuated);
        }
        scrollToTopLeft(timeInSecond, attenuated = true) {
          this._doScroll(0, 1, true, true, timeInSecond, attenuated);
        }
        scrollToTopRight(timeInSecond, attenuated = true) {
          this._doScroll(1, 1, true, true, timeInSecond, attenuated);
        }
        scrollToBottomLeft(timeInSecond, attenuated = true) {
          this._doScroll(0, 0, true, true, timeInSecond, attenuated);
        }
        scrollToBottomRight(timeInSecond, attenuated = true) {
          this._doScroll(1, 0, true, true, timeInSecond, attenuated);
        }
        scrollToOffset(offset, timeInSecond, attenuated = true) {
          const maxScrollOffset = this.getMaxScrollOffset();
          const anchor = v2$1();
          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);
        }
        getScrollOffset() {
          const topDelta = this._getContentTopBoundary() - this._topBoundary;
          const leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          return new Vec2(leftDelta, topDelta);
        }
        getMaxScrollOffset() {
          if (!this._content || !this.view) {
            return Vec2.ZERO;
          }
          const contentSize = this._content._uiProps.uiTransformComp.contentSize;
          let horizontalMaximizeOffset = contentSize.width - this.view.width;
          let verticalMaximizeOffset = contentSize.height - this.view.height;
          horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
          verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
          return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset);
        }
        scrollToPercentHorizontal(percent, timeInSecond, attenuated) {
          this._doScroll(percent, 0, true, false, timeInSecond, attenuated);
        }
        scrollTo(anchor, timeInSecond, attenuated) {
          this._doScroll(anchor.x, anchor.y, true, true, timeInSecond, attenuated);
        }
        scrollToPercentVertical(percent, timeInSecond, attenuated) {
          this._doScroll(0, percent, false, true, timeInSecond, attenuated);
        }
        _doScroll(x, y, applyToHorizontal, applyToVertical, timeInSecond, attenuated = true) {
          assignMoveDeltaOption(x, y, applyToHorizontal, applyToVertical);
          const moveDelta = this._calculateMovePercentDelta(_moveDeltaOptions);
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated);
          } else {
            this._moveContent(moveDelta);
          }
        }
        stopAutoScroll() {
          this._autoScrolling = false;
          this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
        }
        setContentPosition(position) {
          this._setContentPosition(position);
        }
        _setContentPosition(position) {
          if (!this._content) {
            return;
          }
          const 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;
        }
        getContentPosition() {
          return this._getContentPosition();
        }
        _getContentPosition() {
          if (!this._content) {
            return Vec3.ZERO.clone();
          }
          this._contentPos.set(this._content.position);
          return this._contentPos;
        }
        isScrolling() {
          return this._scrolling;
        }
        isAutoScrolling() {
          return this._autoScrolling;
        }
        getScrollEndedEventTiming() {
          return EPSILON;
        }
        start() {
          this._calculateBoundary();
          if (this._content) {
            director.once("director_before_draw", this._adjustContentOutOfBoundary, this);
          }
        }
        onEnable() {
          const self = this;
          {
            self._registerEvent();
            const content = this._content;
            if (content) {
              content.on("size-changed", self._calculateBoundary, self);
              content.on("transform-changed", self._scaleChanged, self);
              const view = self.view;
              if (view) {
                view.node.on("transform-changed", self._scaleChanged, self);
                view.node.on("size-changed", self._calculateBoundary, self);
              }
            }
            self._calculateBoundary();
          }
          self._updateScrollBarState();
        }
        update(dt) {
          const deltaAmount = this._deltaAmount;
          if (this._autoScrolling) {
            this._processAutoScrolling(dt);
            deltaAmount.x = 0;
            deltaAmount.y = 0;
          } else if (deltaAmount.x !== 0 || deltaAmount.y !== 0) {
            this._processDeltaMove(deltaAmount);
            deltaAmount.x = 0;
            deltaAmount.y = 0;
          }
        }
        onDisable() {
          const self = this;
          {
            self._unregisterEvent();
            const content = self.content;
            if (content) {
              content.off("size-changed", self._calculateBoundary, self);
              content.off("transform-changed", self._scaleChanged, self);
              const view = self.view;
              if (view) {
                view.node.off("transform-changed", self._scaleChanged, self);
                view.node.off("size-changed", self._calculateBoundary, self);
              }
            }
          }
          self._deltaAmount.set(0, 0);
          self._hideScrollBar();
          self.stopAutoScroll();
        }
        _registerEvent() {
          const self = this;
          const node = self.node;
          node.on("touch-start", self._onTouchBegan, self, true);
          node.on("touch-move", self._onTouchMoved, self, true);
          node.on("touch-end", self._onTouchEnded, self, true);
          node.on("touch-cancel", self._onTouchCancelled, self, true);
          node.on("mouse-wheel", self._onMouseWheel, self, true);
          node.on("xrui-hover-entered", self._xrHoverEnter, self);
          node.on("xrui-hover-exited", self._xrHoverExit, self);
          input$1.on("handle-input", self._dispatchEventHandleInput, self);
          input$1.on("gamepad-input", self._dispatchEventHandleInput, self);
        }
        _unregisterEvent() {
          const self = this;
          const node = self.node;
          node.off("touch-start", self._onTouchBegan, self, true);
          node.off("touch-move", self._onTouchMoved, self, true);
          node.off("touch-end", self._onTouchEnded, self, true);
          node.off("touch-cancel", self._onTouchCancelled, self, true);
          node.off("mouse-wheel", self._onMouseWheel, self, true);
          node.off("xrui-hover-entered", self._xrHoverEnter, self);
          node.off("xrui-hover-exited", self._xrHoverExit, self);
          input$1.off("handle-input", self._dispatchEventHandleInput, self);
          input$1.off("gamepad-input", self._dispatchEventHandleInput, self);
        }
        _onMouseWheel(event, captureListeners) {
          const self = this;
          if (!self.enabledInHierarchy) {
            return;
          }
          if (self._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          const wheelPrecision = -0.1;
          const scrollY = event.getScrollY();
          const deltaMove = _tempVec3;
          if (self.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (self.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          self._mouseWheelEventElapsedTime = 0;
          self._deltaAmount.add(deltaMove);
          if (!self._stopMouseWheel) {
            self._handlePressLogic();
            self.schedule(this._checkMouseWheel, 1.0 / 60);
            self._stopMouseWheel = true;
          }
          self._stopPropagationIfTargetIsMe(event);
        }
        _onTouchBegan(event, captureListeners) {
          const self = this;
          if (!self.enabledInHierarchy || !self._content) {
            return;
          }
          if (self._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          self._handlePressLogic();
          self._touchMoved = false;
          self._stopPropagationIfTargetIsMe(event);
        }
        _onTouchMoved(event, captureListeners) {
          const self = this;
          if (!self.enabledInHierarchy || !self._content) {
            return;
          }
          if (self._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          const touch = event.touch;
          self._handleMoveLogic(touch);
          if (!self.cancelInnerEvents) {
            return;
          }
          const deltaMove = touch.getUILocation(_tempVec2$1);
          deltaMove.subtract(touch.getUIStartLocation(_tempVec2_1$1));
          if (deltaMove.length() > 7) {
            if (!self._touchMoved && event.target !== self.node) {
              const cancelEvent = new EventTouch(event.getTouches(), event.bubbles, "touch-cancel");
              cancelEvent.touch = event.touch;
              cancelEvent.simulate = true;
              event.target.dispatchEvent(cancelEvent);
              self._touchMoved = true;
            }
          }
          self._stopPropagationIfTargetIsMe(event);
        }
        _onTouchEnded(event, captureListeners) {
          const self = this;
          if (!self.enabledInHierarchy || !self._content || !event) {
            return;
          }
          if (self._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          self._dispatchEvent("touch-up");
          const touch = event.touch;
          self._handleReleaseLogic(touch);
          if (self._touchMoved) {
            event.propagationStopped = true;
          } else {
            self._stopPropagationIfTargetIsMe(event);
          }
        }
        _onTouchCancelled(event, captureListeners) {
          const self = this;
          if (!self.enabledInHierarchy || !self._content) {
            return;
          }
          if (self._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          if (event && !event.simulate) {
            self._handleReleaseLogic(event.touch);
          }
          self._stopPropagationIfTargetIsMe(event);
        }
        _calculateBoundary() {
          const self = this;
          if (self._content && self.view) {
            const layout = self._content.getComponent(Layout);
            if (layout && layout.enabledInHierarchy) {
              layout.updateLayout();
            }
            const viewTrans = self.view;
            const anchorX = viewTrans.width * viewTrans.anchorX;
            const anchorY = viewTrans.height * viewTrans.anchorY;
            self._leftBoundary = -anchorX;
            self._bottomBoundary = -anchorY;
            self._rightBoundary = self._leftBoundary + viewTrans.width;
            self._topBoundary = self._bottomBoundary + viewTrans.height;
            self._moveContentToTopLeft(viewTrans.contentSize);
          }
        }
        _hasNestedViewGroup(event, captureListeners) {
          if (!event || event.eventPhase !== Event.CAPTURING_PHASE) {
            return false;
          }
          if (captureListeners) {
            for (const listener of captureListeners) {
              if (this.node === listener) {
                if (event.target && event.target.getComponent(ViewGroup)) {
                  return true;
                }
                return false;
              }
              if (listener.getComponent(ViewGroup)) {
                return true;
              }
            }
          }
          return false;
        }
        _startInertiaScroll(touchMoveVelocity) {
          _tempVec3.set(touchMoveVelocity);
          _tempVec3.multiplyScalar(MOVEMENT_FACTOR);
          this._startAttenuatingAutoScroll(_tempVec3, touchMoveVelocity);
        }
        _calculateAttenuatedFactor(distance) {
          if (this.brake <= 0) {
            return 1 - this.brake;
          }
          return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008));
        }
        _startAttenuatingAutoScroll(deltaMove, initialVelocity) {
          const targetDelta = deltaMove.clone();
          targetDelta.normalize();
          if (this._content && this.view) {
            const contentSize = this._content._uiProps.uiTransformComp.contentSize;
            const scrollViewSize = this.view.contentSize;
            const totalMoveWidth = contentSize.width - scrollViewSize.width;
            const totalMoveHeight = contentSize.height - scrollViewSize.height;
            const attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);
            const 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;
          }
          const originalMoveLength = deltaMove.length();
          let factor = targetDelta.length() / originalMoveLength;
          if (this.brake > 0 && factor > 7) {
            factor = Math.sqrt(factor);
            targetDelta.set(deltaMove);
            targetDelta.multiplyScalar(factor + 1);
          } else {
            targetDelta.add(deltaMove);
          }
          let 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);
        }
        _calculateAutoScrollTimeByInitialSpeed(initialSpeed) {
          return Math.sqrt(Math.sqrt(initialSpeed / 5));
        }
        _startAutoScroll(deltaMove, timeInSecond, attenuated = false) {
          const self = this;
          const adjustedDeltaMove = self._flattenVectorByDirection(deltaMove);
          self._autoScrolling = true;
          self._autoScrollTargetDelta = adjustedDeltaMove;
          self._autoScrollAttenuate = attenuated;
          Vec3.copy(self._autoScrollStartPosition, self._getContentPosition());
          self._autoScrollTotalTime = timeInSecond;
          self._autoScrollAccumulatedTime = 0;
          self._autoScrollBraking = false;
          self._isScrollEndedWithThresholdEventFired = false;
          self._autoScrollBrakingStartPosition.set(0, 0, 0);
          const currentOutOfBoundary = self._getHowMuchOutOfBoundary();
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            this._autoScrollCurrentlyOutOfBoundary = true;
          }
        }
        _calculateTouchMoveVelocity() {
          const out = new Vec3();
          let totalTime = 0;
          totalTime = this._touchMoveTimeDeltas.reduce((a, b) => a + b, totalTime);
          if (totalTime <= 0 || totalTime >= 0.5) {
            out.set(Vec3.ZERO);
          } else {
            let totalMovement = _tempVec3;
            totalMovement.set(0, 0, 0);
            totalMovement = this._touchMoveDisplacements.reduce((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;
        }
        _flattenVectorByDirection(vector) {
          if (!this.horizontal) vector.x = 0;
          if (!this.vertical) vector.y = 0;
          return vector;
        }
        _moveContent(deltaMove, canStartBounceBack) {
          const 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);
          const outOfBoundary = this._getHowMuchOutOfBoundary();
          _tempVec2$1.set(outOfBoundary.x, outOfBoundary.y);
          this._updateScrollBar(_tempVec2$1);
          if (this.elastic && canStartBounceBack) {
            this._startBounceBackIfNeeded();
          }
        }
        _getContentLeftBoundary() {
          if (!this._content) {
            return -1;
          }
          const contentPos = this._getContentPosition();
          const uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.x - uiTrans.anchorX * uiTrans.width;
        }
        _getContentRightBoundary() {
          if (!this._content) {
            return -1;
          }
          const uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentLeftBoundary() + uiTrans.width;
        }
        _getContentTopBoundary() {
          if (!this._content) {
            return -1;
          }
          const uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentBottomBoundary() + uiTrans.height;
        }
        _getContentBottomBoundary() {
          if (!this._content) {
            return -1;
          }
          const contentPos = this._getContentPosition();
          const uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.y - uiTrans.anchorY * uiTrans.height;
        }
        _getHowMuchOutOfBoundary(addition) {
          if (!addition) {
            addition = Vec3.ZERO;
          }
          if (addition.equals(Vec3.ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) {
            return this._outOfBoundaryAmount;
          }
          const outOfBoundaryAmount = new Vec3();
          const tempLeftBoundary = this._getContentLeftBoundary();
          const 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);
          }
          const tempTopBoundary = this._getContentTopBoundary();
          const 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;
        }
        _updateScrollBar(outOfBoundary) {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onScroll(outOfBoundary);
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onScroll(outOfBoundary);
          }
        }
        _onScrollBarTouchBegan() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchBegan();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchBegan();
          }
        }
        _onScrollBarTouchEnded() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchEnded();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchEnded();
          }
        }
        _dispatchEvent(event) {
          if (event === "scroll-ended") {
            this._scrollEventEmitMask = 0;
          } else if (event === "scroll-to-top" || event === "scroll-to-bottom" || event === "scroll-to-left" || event === "scroll-to-right") {
            const 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);
        }
        _adjustContentOutOfBoundary() {
          if (!this._content) {
            return;
          }
          this._outOfBoundaryAmountDirty = true;
          const outOfBoundary = this._getHowMuchOutOfBoundary();
          const _isOutOfBoundary = !outOfBoundary.equals(Vec3.ZERO, EPSILON);
          if (_isOutOfBoundary) {
            _tempVec3.set(this._getContentPosition());
            _tempVec3.add(outOfBoundary);
            this._setContentPosition(_tempVec3);
            this._updateScrollBar(Vec2.ZERO);
          }
        }
        _hideScrollBar() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.hide();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.hide();
          }
        }
        _updateScrollBarState() {
          const self = this;
          if (!self._content || !self.view) {
            return;
          }
          const viewTrans = self.view;
          const uiTrans = self._content._uiProps.uiTransformComp;
          const verticalScrollBar = self._verticalScrollBar;
          if (verticalScrollBar && verticalScrollBar.isValid) {
            if (uiTrans.height < viewTrans.height || approx(uiTrans.height, viewTrans.height)) {
              verticalScrollBar.hide();
            } else {
              verticalScrollBar.show();
            }
          }
          const horizontalScrollBar = self._horizontalScrollBar;
          if (horizontalScrollBar && horizontalScrollBar.isValid) {
            if (uiTrans.width < viewTrans.width || approx(uiTrans.width, viewTrans.width)) {
              horizontalScrollBar.hide();
            } else {
              horizontalScrollBar.show();
            }
          }
        }
        _stopPropagationIfTargetIsMe(event) {
          if (event.eventPhase === Event.AT_TARGET && event.target === this.node) {
            event.propagationStopped = true;
          }
        }
        _processDeltaMove(deltaMove) {
          this._scrollChildren(deltaMove);
          this._gatherTouchMove(deltaMove);
        }
        _handleMoveLogic(touch) {
          this._getLocalAxisAlignDelta(this._deltaPos, touch);
          this._deltaAmount.add(this._deltaPos);
        }
        _handleReleaseLogic(touch) {
          const self = this;
          self._getLocalAxisAlignDelta(self._deltaPos, touch);
          self._gatherTouchMove(self._deltaPos);
          self._processInertiaScroll();
          if (self._scrolling) {
            self._scrolling = false;
            if (!self._autoScrolling) {
              self._dispatchEvent("scroll-ended");
            }
          }
        }
        _getLocalAxisAlignDelta(out, touch) {
          const uiTransformComp = this.node._uiProps.uiTransformComp;
          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(out, _tempVec3, _tempVec3_1);
          }
        }
        _scrollChildren(deltaMove) {
          const self = this;
          self._clampDelta(deltaMove);
          const realMove = deltaMove;
          let outOfBoundary;
          if (self.elastic) {
            outOfBoundary = self._getHowMuchOutOfBoundary();
            realMove.x *= outOfBoundary.x === 0 ? 1 : 0.5;
            realMove.y *= outOfBoundary.y === 0 ? 1 : 0.5;
          }
          if (!self.elastic) {
            outOfBoundary = self._getHowMuchOutOfBoundary(realMove);
            realMove.add(outOfBoundary);
          }
          let verticalScrollEventType = "";
          let horizontalScrollEventType = "";
          if (self._content) {
            const {
              anchorX,
              anchorY,
              width,
              height
            } = self._content._uiProps.uiTransformComp;
            const pos = self._content.position || Vec3.ZERO;
            if (self.vertical) {
              if (realMove.y > 0) {
                const icBottomPos = pos.y - anchorY * height;
                if (icBottomPos + realMove.y >= self._bottomBoundary) {
                  verticalScrollEventType = "scroll-to-bottom";
                }
              } else if (realMove.y < 0) {
                const icTopPos = pos.y - anchorY * height + height;
                if (icTopPos + realMove.y <= self._topBoundary) {
                  verticalScrollEventType = "scroll-to-top";
                }
              }
            }
            if (self.horizontal) {
              if (realMove.x < 0) {
                const icRightPos = pos.x - anchorX * width + width;
                if (icRightPos + realMove.x <= self._rightBoundary) {
                  horizontalScrollEventType = "scroll-to-right";
                }
              } else if (realMove.x > 0) {
                const icLeftPos = pos.x - anchorX * width;
                if (icLeftPos + realMove.x >= self._leftBoundary) {
                  horizontalScrollEventType = "scroll-to-left";
                }
              }
            }
          }
          self._moveContent(realMove, false);
          if (self.horizontal && realMove.x !== 0 || self.vertical && realMove.y !== 0) {
            if (!self._scrolling) {
              self._scrolling = true;
              self._dispatchEvent("scroll-began");
            }
            self._dispatchEvent("scrolling");
          }
          if (verticalScrollEventType !== "") {
            self._dispatchEvent(verticalScrollEventType);
          }
          if (horizontalScrollEventType !== "") {
            self._dispatchEvent(horizontalScrollEventType);
          }
        }
        _handlePressLogic() {
          const self = this;
          if (self._autoScrolling) {
            self._dispatchEvent("scroll-ended");
          }
          self._autoScrolling = false;
          self._isBouncing = false;
          self._touchMovePreviousTimestamp = getTimeInMilliseconds();
          self._touchMoveDisplacements.length = 0;
          self._touchMoveTimeDeltas.length = 0;
          self._onScrollBarTouchBegan();
        }
        _clampDelta(out) {
          if (this._content && this.view) {
            const scrollViewSize = this.view.contentSize;
            const uiTrans = this._content._uiProps.uiTransformComp;
            if (uiTrans.width < scrollViewSize.width) {
              out.x = 0;
            }
            if (uiTrans.height < scrollViewSize.height) {
              out.y = 0;
            }
          }
        }
        _gatherTouchMove(delta) {
          const self = this;
          const clampDt = delta.clone();
          self._clampDelta(clampDt);
          while (self._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
            self._touchMoveDisplacements.shift();
            self._touchMoveTimeDeltas.shift();
          }
          self._touchMoveDisplacements.push(clampDt);
          const timeStamp = getTimeInMilliseconds();
          self._touchMoveTimeDeltas.push((timeStamp - self._touchMovePreviousTimestamp) / 1000);
          self._touchMovePreviousTimestamp = timeStamp;
        }
        _startBounceBackIfNeeded() {
          const self = this;
          if (!self.elastic) {
            return false;
          }
          const bounceBackAmount = self._getHowMuchOutOfBoundary();
          self._clampDelta(bounceBackAmount);
          if (bounceBackAmount.equals(Vec3.ZERO, EPSILON)) {
            return false;
          }
          const bounceBackTime = Math.max(self.bounceDuration, 0);
          self._startAutoScroll(bounceBackAmount, bounceBackTime, true);
          if (!self._isBouncing) {
            if (bounceBackAmount.y > 0) {
              self._dispatchEvent("bounce-top");
            }
            if (bounceBackAmount.y < 0) {
              self._dispatchEvent("bounce-bottom");
            }
            if (bounceBackAmount.x > 0) {
              self._dispatchEvent("bounce-right");
            }
            if (bounceBackAmount.x < 0) {
              self._dispatchEvent("bounce-left");
            }
            self._isBouncing = true;
          }
          return true;
        }
        _processInertiaScroll() {
          const bounceBackStarted = this._startBounceBackIfNeeded();
          if (!bounceBackStarted && this.inertia) {
            const touchMoveVelocity = this._calculateTouchMoveVelocity();
            if (!touchMoveVelocity.equals(Vec3.ZERO, EPSILON) && this.brake < 1) {
              this._startInertiaScroll(touchMoveVelocity);
            }
          }
          this._onScrollBarTouchEnded();
        }
        _isOutOfBoundary() {
          const outOfBoundary = this._getHowMuchOutOfBoundary();
          return !outOfBoundary.equals(Vec3.ZERO, EPSILON);
        }
        _isNecessaryAutoScrollBrake() {
          const self = this;
          if (self._autoScrollBraking) {
            return true;
          }
          if (self._isOutOfBoundary()) {
            if (!self._autoScrollCurrentlyOutOfBoundary) {
              self._autoScrollCurrentlyOutOfBoundary = true;
              self._autoScrollBraking = true;
              Vec3.copy(self._autoScrollBrakingStartPosition, self._getContentPosition());
              return true;
            }
          } else {
            self._autoScrollCurrentlyOutOfBoundary = false;
          }
          return false;
        }
        _processAutoScrolling(dt) {
          const self = this;
          const isAutoScrollBrake = self._isNecessaryAutoScrollBrake();
          const brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
          self._autoScrollAccumulatedTime += dt * (1 / brakingFactor);
          let percentage = Math.min(1, self._autoScrollAccumulatedTime / self._autoScrollTotalTime);
          if (self._autoScrollAttenuate) {
            percentage = quintEaseOut(percentage);
          }
          const clonedAutoScrollTargetDelta = self._autoScrollTargetDelta.clone();
          clonedAutoScrollTargetDelta.multiplyScalar(percentage);
          const clonedAutoScrollStartPosition = self._autoScrollStartPosition.clone();
          clonedAutoScrollStartPosition.add(clonedAutoScrollTargetDelta);
          let reachedEnd = Math.abs(percentage - 1) <= EPSILON;
          const fireEvent = Math.abs(percentage - 1) <= self.getScrollEndedEventTiming();
          if (fireEvent && !self._isScrollEndedWithThresholdEventFired) {
            self._dispatchEvent("scroll-ended-with-threshold");
            self._isScrollEndedWithThresholdEventFired = true;
          }
          if (self.elastic) {
            const brakeOffsetPosition = clonedAutoScrollStartPosition.clone();
            brakeOffsetPosition.subtract(self._autoScrollBrakingStartPosition);
            if (isAutoScrollBrake) {
              brakeOffsetPosition.multiplyScalar(brakingFactor);
            }
            clonedAutoScrollStartPosition.set(self._autoScrollBrakingStartPosition);
            clonedAutoScrollStartPosition.add(brakeOffsetPosition);
          } else {
            const moveDelta = clonedAutoScrollStartPosition.clone();
            moveDelta.subtract(self.getContentPosition());
            const outOfBoundary = self._getHowMuchOutOfBoundary(moveDelta);
            if (!outOfBoundary.equals(Vec3.ZERO, EPSILON)) {
              clonedAutoScrollStartPosition.add(outOfBoundary);
              reachedEnd = true;
            }
          }
          if (reachedEnd) {
            self._autoScrolling = false;
          }
          const deltaMove = clonedAutoScrollStartPosition.clone();
          deltaMove.subtract(self._getContentPosition());
          self._clampDelta(deltaMove);
          self._moveContent(deltaMove, reachedEnd);
          self._dispatchEvent("scrolling");
          if (!self._autoScrolling) {
            self._isBouncing = false;
            self._scrolling = false;
            self._dispatchEvent("scroll-ended");
          }
        }
        _checkMouseWheel(dt) {
          const self = this;
          const currentOutOfBoundary = self._getHowMuchOutOfBoundary();
          const maxElapsedTime = 0.1;
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            self._processInertiaScroll();
            if (self._scrolling) {
              self._scrolling = false;
              if (!self._autoScrolling) {
                self._dispatchEvent("scroll-ended");
              }
            }
            self.unschedule(self._checkMouseWheel);
            self._stopMouseWheel = false;
            return;
          }
          self._mouseWheelEventElapsedTime += dt;
          if (self._mouseWheelEventElapsedTime > maxElapsedTime) {
            self._onScrollBarTouchEnded();
            if (self._scrolling) {
              self._scrolling = false;
              if (!self._autoScrolling) {
                self._dispatchEvent("scroll-ended");
              }
            }
            self.unschedule(self._checkMouseWheel);
            self._stopMouseWheel = false;
          }
        }
        _calculateMovePercentDelta(options) {
          const anchor = options.anchor;
          const applyToHorizontal = options.applyToHorizontal;
          const applyToVertical = options.applyToVertical;
          const self = this;
          self._calculateBoundary();
          anchor.clampf(Vec2.ZERO, Vec2.ONE);
          let bottomDelta = self._getContentBottomBoundary() - self._bottomBoundary;
          bottomDelta = -bottomDelta;
          let leftDelta = self._getContentLeftBoundary() - self._leftBoundary;
          leftDelta = -leftDelta;
          const moveDelta = new Vec3();
          if (self._content && self.view) {
            let totalScrollDelta = 0;
            const uiTrans = self._content._uiProps.uiTransformComp;
            const contentSize = uiTrans.contentSize;
            const scrollSize = self.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;
        }
        _moveContentToTopLeft(scrollViewSize) {
          const self = this;
          let bottomDelta = self._getContentBottomBoundary() - self._bottomBoundary;
          bottomDelta = -bottomDelta;
          const moveDelta = new Vec3();
          let totalScrollDelta = 0;
          let leftDelta = self._getContentLeftBoundary() - self._leftBoundary;
          leftDelta = -leftDelta;
          if (self._content) {
            const uiTrans = self._content._uiProps.uiTransformComp;
            const 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;
            }
          }
          self._updateScrollBarState();
          self._moveContent(moveDelta);
          self._adjustContentOutOfBoundary();
        }
        _scaleChanged(value) {
          if (value === 4) {
            this._calculateBoundary();
          }
        }
        _xrHoverEnter(event) {
          if (event.deviceType === 1) {
            this._hoverIn = 1;
          } else if (event.deviceType === 2) {
            this._hoverIn = 2;
          }
        }
        _xrHoverExit(event) {
          this._hoverIn = 0;
        }
        _dispatchEventHandleInput(event) {
          let handleInputDevice;
          if (event instanceof EventGamepad) {
            handleInputDevice = event.gamepad;
          } else if (event instanceof EventHandle) {
            handleInputDevice = event.handleInputDevice;
          }
          let value;
          if (!this.enabledInHierarchy || this._hoverIn === 0) {
            return;
          }
          if (this._hoverIn === 1) {
            value = handleInputDevice.leftStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          } else if (this._hoverIn === 2) {
            value = handleInputDevice.rightStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          }
        }
        _xrThumbStickMove(event) {
          const self = this;
          if (!self.enabledInHierarchy) {
            return;
          }
          const wheelPrecision = -62.5;
          const scrollY = event.y;
          const deltaMove = _tempVec3;
          if (self.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (self.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          self._mouseWheelEventElapsedTime = 0;
          self._deltaAmount.add(deltaMove);
          if (!self._stopMouseWheel) {
            self._handlePressLogic();
            self.schedule(self._checkMouseWheel, 1.0 / 60, NaN, 0);
            self._stopMouseWheel = true;
          }
        }
      }, _class3$7.EventType = ScrollViewEventType, _class3$7), (_initializer$c = applyDecoratedInitializer(_class2$c.prototype, "bounceDuration", [serializable$l], function () {
        return 1;
      }), _initializer2$a = applyDecoratedInitializer(_class2$c.prototype, "brake", [serializable$l], function () {
        return 0.5;
      }), _initializer3$7 = applyDecoratedInitializer(_class2$c.prototype, "elastic", [serializable$l], function () {
        return true;
      }), _initializer4$6 = applyDecoratedInitializer(_class2$c.prototype, "inertia", [serializable$l], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$c.prototype, "content", [_dec4$7], Object.getOwnPropertyDescriptor(_class2$c.prototype, "content"), _class2$c.prototype), _initializer5$4 = applyDecoratedInitializer(_class2$c.prototype, "horizontal", [serializable$l], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$c.prototype, "horizontalScrollBar", [_dec5$7], Object.getOwnPropertyDescriptor(_class2$c.prototype, "horizontalScrollBar"), _class2$c.prototype), _initializer6$3 = applyDecoratedInitializer(_class2$c.prototype, "vertical", [serializable$l], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$c.prototype, "verticalScrollBar", [_dec6$3], Object.getOwnPropertyDescriptor(_class2$c.prototype, "verticalScrollBar"), _class2$c.prototype), _initializer7$3 = applyDecoratedInitializer(_class2$c.prototype, "cancelInnerEvents", [serializable$l], function () {
        return true;
      }), _initializer8$3 = applyDecoratedInitializer(_class2$c.prototype, "scrollEvents", [_dec7$1, serializable$l], function () {
        return [];
      }), _initializer9$3 = applyDecoratedInitializer(_class2$c.prototype, "_content", [serializable$l], function () {
        return null;
      }), _initializer10$3 = applyDecoratedInitializer(_class2$c.prototype, "_horizontalScrollBar", [serializable$l], function () {
        return null;
      }), _initializer11$3 = applyDecoratedInitializer(_class2$c.prototype, "_verticalScrollBar", [serializable$l], function () {
        return null;
      })), _class2$c)) || _class$e) || _class$e) || _class$e); exports({ ScrollView: ScrollView, ScrollViewComponent: ScrollView });
      legacyCC.ScrollView = ScrollView;

      var _dec$d, _dec2$a, _dec3$a, _dec4$6, _dec5$6, _dec6$2, _class$d, _class2$b, _initializer$b, _initializer2$9, _initializer3$6, _initializer4$5, _class3$6;
      const _tempPos$1 = new Vec3();
      const Direction$1 = {
        "Horizontal": 0,
        "Vertical": 1
      };
      ccenum(Direction$1);
      let Slider = (_dec$d = ccclass$H('cc.Slider'), _dec2$a = executionOrder$1(110), _dec3$a = requireComponent(UITransform), _dec4$6 = type$a(Sprite), _dec5$6 = type$a(Direction$1), _dec6$2 = type$a([EventHandler]), _dec$d(_class$d = _dec2$a(_class$d = _dec3$a(_class$d = (_class2$b = (_class3$6 = class Slider extends Component {
        get handle() {
          return this._handle;
        }
        set handle(value) {
          if (this._handle === value) {
            return;
          }
          this._handle = value;
        }
        get direction() {
          return this._direction;
        }
        set direction(value) {
          if (this._direction === value) {
            return;
          }
          this._direction = value;
          this._changeLayout();
        }
        get progress() {
          return this._progress;
        }
        set progress(value) {
          if (this._progress === value) {
            return;
          }
          this._progress = value;
          this._updateHandlePosition();
        }
        constructor() {
          super();
          this.slideEvents = _initializer$b && _initializer$b();
          this._handle = _initializer2$9 && _initializer2$9();
          this._direction = _initializer3$6 && _initializer3$6();
          this._progress = _initializer4$5 && _initializer4$5();
          this._offset = new Vec3();
          this._dragging = false;
          this._touchHandle = false;
          this._handleLocalPos = new Vec3();
          this._touchPos = new Vec3();
        }
        __preload() {
          this._updateHandlePosition();
        }
        onEnable() {
          this._updateHandlePosition();
          this.node.on("touch-start", this._onTouchBegan, this);
          this.node.on("touch-move", this._onTouchMoved, this);
          this.node.on("touch-end", this._onTouchEnded, this);
          this.node.on("touch-cancel", this._onTouchCancelled, this);
          this.node.on("xrui-hover-stay", this._xrHoverStay, this);
          this.node.on("xrui-click", this._xrClick, this);
          this.node.on("xrui-unclick", this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.on("touch-start", this._onHandleDragStart, this);
            this._handle.node.on("touch-move", this._onTouchMoved, this);
            this._handle.node.on("touch-end", this._onTouchEnded, this);
          }
        }
        onDisable() {
          this.node.off("touch-start", this._onTouchBegan, this);
          this.node.off("touch-move", this._onTouchMoved, this);
          this.node.off("touch-end", this._onTouchEnded, this);
          this.node.off("touch-cancel", this._onTouchCancelled, this);
          this.node.off("xrui-hover-stay", this._xrHoverStay, this);
          this.node.off("xrui-click", this._xrClick, this);
          this.node.off("xrui-unclick", this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.off("touch-start", this._onHandleDragStart, this);
            this._handle.node.off("touch-move", this._onTouchMoved, this);
            this._handle.node.off("touch-end", this._onTouchEnded, this);
          }
        }
        _onHandleDragStart(event) {
          if (!event || !this._handle || !this._handle.node._uiProps.uiTransformComp) {
            return;
          }
          this._dragging = true;
          this._touchHandle = true;
          const 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;
        }
        _onTouchBegan(event) {
          if (!this._handle || !event) {
            return;
          }
          this._dragging = true;
          if (!this._touchHandle) {
            this._handleSliderLogic(event.touch);
          }
          event.propagationStopped = true;
        }
        _onTouchMoved(event) {
          if (!this._dragging || !event) {
            return;
          }
          this._handleSliderLogic(event.touch);
          event.propagationStopped = true;
        }
        _onTouchEnded(event) {
          this._dragging = false;
          this._touchHandle = false;
          this._offset = new Vec3();
          if (event) {
            event.propagationStopped = true;
          }
        }
        _onTouchCancelled(event) {
          this._dragging = false;
          if (event) {
            event.propagationStopped = true;
          }
        }
        _handleSliderLogic(touch) {
          this._updateProgress(touch);
          this._emitSlideEvent();
        }
        _emitSlideEvent() {
          EventHandler.emitEvents(this.slideEvents, this);
          this.node.emit('slide', this);
        }
        _updateProgress(touch) {
          if (!this._handle || !touch) {
            return;
          }
          const touchPos = touch.getUILocation();
          Vec3.set(this._touchPos, touchPos.x, touchPos.y, 0);
          const uiTrans = this.node._uiProps.uiTransformComp;
          const localTouchPos = uiTrans.convertToNodeSpaceAR(this._touchPos, _tempPos$1);
          if (this.direction === 0) {
            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);
          }
        }
        _updateHandlePosition() {
          if (!this._handle) {
            return;
          }
          this._handleLocalPos.set(this._handle.node.position);
          const uiTrans = this.node._uiProps.uiTransformComp;
          if (this._direction === 0) {
            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);
        }
        _changeLayout() {
          const uiTrans = this.node._uiProps.uiTransformComp;
          const contentSize = uiTrans.contentSize;
          uiTrans.setContentSize(contentSize.height, contentSize.width);
          if (this._handle) {
            const pos = this._handle.node.position;
            if (this._direction === 0) {
              this._handle.node.setPosition(pos.x, 0, pos.z);
            } else {
              this._handle.node.setPosition(0, pos.y, pos.z);
            }
            this._updateHandlePosition();
          }
        }
        _xrHandleProgress(point) {
          if (!this._touchHandle) {
            const uiTrans = this.node._uiProps.uiTransformComp;
            uiTrans.convertToNodeSpaceAR(point, _tempPos$1);
            if (this.direction === 0) {
              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);
            }
          }
        }
        _xrClick(event) {
          if (!this._handle) {
            return;
          }
          this._dragging = true;
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        }
        _xrUnClick() {
          this._dragging = false;
          this._touchHandle = false;
        }
        _xrHoverStay(event) {
          if (!this._dragging) {
            return;
          }
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        }
      }, _class3$6.Direction = Direction$1, _class3$6), (_applyDecoratedDescriptor(_class2$b.prototype, "handle", [_dec4$6], Object.getOwnPropertyDescriptor(_class2$b.prototype, "handle"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "direction", [_dec5$6], Object.getOwnPropertyDescriptor(_class2$b.prototype, "direction"), _class2$b.prototype), _initializer$b = applyDecoratedInitializer(_class2$b.prototype, "slideEvents", [_dec6$2, serializable$l], function () {
        return [];
      }), _initializer2$9 = applyDecoratedInitializer(_class2$b.prototype, "_handle", [serializable$l], function () {
        return null;
      }), _initializer3$6 = applyDecoratedInitializer(_class2$b.prototype, "_direction", [serializable$l], function () {
        return 0;
      }), _initializer4$5 = applyDecoratedInitializer(_class2$b.prototype, "_progress", [serializable$l], function () {
        return 0.1;
      })), _class2$b)) || _class$d) || _class$d) || _class$d); exports({ Slider: Slider, SliderComponent: Slider });
      legacyCC.Slider = Slider;

      function extendsEnum(...enums) {
        return Object.assign({}, ...enums);
      }

      var _dec$c, _dec2$9, _dec3$9, _dec4$5, _dec5$5, _class$c, _class2$a, _initializer$a, _initializer2$8, _initializer3$5, _class3$5;
      const ToggleEventType = {
        "TOGGLE": "toggle"
      };
      let Toggle = (_dec$c = ccclass$H('cc.Toggle'), _dec2$9 = executionOrder$1(110), _dec3$9 = requireComponent(UITransform), _dec4$5 = type$a(Sprite), _dec5$5 = type$a([EventHandler]), _dec$c(_class$c = _dec2$9(_class$c = _dec3$9(_class$c = (_class2$a = (_class3$5 = class Toggle extends Button {
        get isChecked() {
          return this._isChecked;
        }
        set isChecked(value) {
          this._set(value);
        }
        get checkMark() {
          return this._checkMark;
        }
        set checkMark(value) {
          if (this._checkMark === value) {
            return;
          }
          this._checkMark = value;
        }
        set _resizeToTarget(value) {
          if (value) {
            this._resizeNodeToTargetNode();
          }
        }
        get _toggleContainer() {
          const parent = this.node.parent;
          if (legacyCC.Node.isNode(parent)) {
            return parent.getComponent('cc.ToggleContainer');
          }
          return null;
        }
        constructor() {
          super();
          this.checkEvents = _initializer$a && _initializer$a();
          this._isChecked = _initializer2$8 && _initializer2$8();
          this._checkMark = _initializer3$5 && _initializer3$5();
        }
        _internalToggle() {
          this.isChecked = !this.isChecked;
        }
        _set(value, emitEvent = true) {
          if (this._isChecked == value) return;
          this._isChecked = value;
          const 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();
          }
        }
        playEffect() {
          if (this._checkMark) {
            this._checkMark.node.active = this._isChecked;
          }
        }
        setIsCheckedWithoutNotify(value) {
          this._set(value, false);
        }
        onEnable() {
          super.onEnable();
          this.playEffect();
          {
            this.node.on(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        }
        onDisable() {
          super.onDisable();
          {
            this.node.off(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        }
        _emitToggleEvents() {
          this.node.emit(Toggle.EventType.TOGGLE, this);
          if (this.checkEvents) {
            EventHandler.emitEvents(this.checkEvents, this);
          }
        }
      }, _class3$5.EventType = extendsEnum(ToggleEventType, ButtonEventType), _class3$5), (_applyDecoratedDescriptor(_class2$a.prototype, "checkMark", [_dec4$5], Object.getOwnPropertyDescriptor(_class2$a.prototype, "checkMark"), _class2$a.prototype), _initializer$a = applyDecoratedInitializer(_class2$a.prototype, "checkEvents", [_dec5$5, serializable$l], function () {
        return [];
      }), _initializer2$8 = applyDecoratedInitializer(_class2$a.prototype, "_isChecked", [serializable$l], function () {
        return true;
      }), _initializer3$5 = applyDecoratedInitializer(_class2$a.prototype, "_checkMark", [serializable$l], function () {
        return null;
      })), _class2$a)) || _class$c) || _class$c) || _class$c); exports({ Toggle: Toggle, ToggleComponent: Toggle });
      legacyCC.Toggle = Toggle;

      var _dec$b, _dec2$8, _dec3$8, _class$b, _class2$9, _initializer$9, _initializer2$7;
      let ToggleContainer = (_dec$b = ccclass$H('cc.ToggleContainer'), _dec2$8 = executionOrder$1(110), _dec3$8 = type$a([EventHandler]), _dec$b(_class$b = _dec2$8(_class$b = (_class2$9 = class ToggleContainer extends Component {
        get allowSwitchOff() {
          return this._allowSwitchOff;
        }
        set allowSwitchOff(value) {
          this._allowSwitchOff = value;
        }
        constructor() {
          super();
          this._allowSwitchOff = _initializer$9 && _initializer$9();
          this.checkEvents = _initializer2$7 && _initializer2$7();
        }
        get toggleItems() {
          return this.node.children.map(item => {
            const toggle = item.getComponent('cc.Toggle');
            if (toggle && toggle.enabled) {
              return toggle;
            }
            return null;
          }).filter(Boolean);
        }
        onEnable() {
          this.ensureValidState();
          this.node.on("child-added", this.ensureValidState, this);
          this.node.on("child-removed", this.ensureValidState, this);
        }
        onDisable() {
          this.node.off("child-added", this.ensureValidState, this);
          this.node.off("child-removed", this.ensureValidState, this);
        }
        activeToggles() {
          return this.toggleItems.filter(x => x.isChecked);
        }
        anyTogglesChecked() {
          return !!this.toggleItems.find(x => x.isChecked);
        }
        notifyToggleCheck(toggle, emitEvent = true) {
          if (!this.enabledInHierarchy) {
            return;
          }
          for (let i = 0; i < this.toggleItems.length; i++) {
            const 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);
          }
        }
        ensureValidState() {
          const toggles = this.toggleItems;
          if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) {
            const toggle = toggles[0];
            toggle.isChecked = true;
            this.notifyToggleCheck(toggle);
          }
          const activeToggles = this.activeToggles();
          if (activeToggles.length > 1) {
            const firstToggle = activeToggles[0];
            for (let i = 0; i < activeToggles.length; ++i) {
              const toggle = activeToggles[i];
              if (toggle === firstToggle) {
                continue;
              }
              toggle.isChecked = false;
            }
          }
        }
      }, (_initializer$9 = applyDecoratedInitializer(_class2$9.prototype, "_allowSwitchOff", [serializable$l], function () {
        return false;
      }), _initializer2$7 = applyDecoratedInitializer(_class2$9.prototype, "checkEvents", [_dec3$8, serializable$l], function () {
        return [];
      })), _class2$9)) || _class$b) || _class$b); exports({ ToggleContainer: ToggleContainer, ToggleContainerComponent: ToggleContainer });
      legacyCC.ToggleContainer = ToggleContainer;

      var _dec$a, _dec2$7, _dec3$7, _dec4$4, _dec5$4, _class$a, _class2$8, _initializer$8, _initializer2$6, _initializer3$4, _initializer4$4, _initializer5$3, _initializer6$2, _initializer7$2, _initializer8$2, _initializer9$2, _initializer10$2, _initializer11$2, _initializer12$2, _initializer13, _initializer14, _initializer15, _initializer16, _initializer17, _initializer18, _class3$4;
      const _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.scale.x, widgetNode.parent.scale.y);
        } else {
          _tempScale.set(0, 0);
        }
        let scaleX = _tempScale.x;
        let scaleY = _tempScale.y;
        let translateX = 0;
        let translateY = 0;
        for (let node = widgetNode.parent;;) {
          if (!node) {
            out_inverseTranslate.x = out_inverseTranslate.y = 0;
            out_inverseScale.x = out_inverseScale.y = 1;
            return;
          }
          const pos = node.position;
          translateX += pos.x;
          translateY += pos.y;
          node = node.parent;
          if (node !== target) {
            if (node) {
              _tempScale.set(node.scale.x, node.scale.y);
            } else {
              _tempScale.set(0, 0);
            }
            const sx = _tempScale.x;
            const 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;
      }
      const AlignMode = {
        "ONCE": 0,
        "ALWAYS": 1,
        "ON_WINDOW_RESIZE": 2
      };
      ccenum(AlignMode);
      const AlignFlags = {
        "TOP": 1,
        "MID": 2,
        "BOT": 4,
        "LEFT": 8,
        "CENTER": 16,
        "RIGHT": 32,
        "HORIZONTAL": 56,
        "VERTICAL": 7
      };
      const TOP_BOT = 1 | 4;
      const LEFT_RIGHT = 8 | 32;
      let Widget = (_dec$a = ccclass$H('cc.Widget'), _dec2$7 = executionOrder$1(110), _dec3$7 = requireComponent(UITransform), _dec4$4 = type$a(Node$1), _dec5$4 = type$a(AlignMode), _dec$a(_class$a = _dec2$7(_class$a = _dec3$7(_class$a = (_class2$8 = (_class3$4 = class Widget extends Component {
        constructor() {
          super();
          this._lastPos = new Vec3();
          this._lastSize = new Size$1();
          this._dirty = true;
          this._hadAlignOnce = false;
          this._alignFlags = _initializer$8 && _initializer$8();
          this._target = _initializer2$6 && _initializer2$6();
          this._left = _initializer3$4 && _initializer3$4();
          this._right = _initializer4$4 && _initializer4$4();
          this._top = _initializer5$3 && _initializer5$3();
          this._bottom = _initializer6$2 && _initializer6$2();
          this._horizontalCenter = _initializer7$2 && _initializer7$2();
          this._verticalCenter = _initializer8$2 && _initializer8$2();
          this._isAbsLeft = _initializer9$2 && _initializer9$2();
          this._isAbsRight = _initializer10$2 && _initializer10$2();
          this._isAbsTop = _initializer11$2 && _initializer11$2();
          this._isAbsBottom = _initializer12$2 && _initializer12$2();
          this._isAbsHorizontalCenter = _initializer13 && _initializer13();
          this._isAbsVerticalCenter = _initializer14 && _initializer14();
          this._originalWidth = _initializer15 && _initializer15();
          this._originalHeight = _initializer16 && _initializer16();
          this._alignMode = _initializer17 && _initializer17();
          this._lockFlags = _initializer18 && _initializer18();
        }
        get target() {
          return this._target;
        }
        set target(value) {
          if (this._target === value) {
            return;
          }
          this._unregisterTargetEvents();
          this._target = value;
          this._registerTargetEvents();
          this._validateTargetInDEV();
          this._recursiveDirty();
        }
        get isAlignTop() {
          return (this._alignFlags & 1) > 0;
        }
        set isAlignTop(value) {
          this._setAlign(1, value);
          this._recursiveDirty();
        }
        get isAlignBottom() {
          return (this._alignFlags & 4) > 0;
        }
        set isAlignBottom(value) {
          this._setAlign(4, value);
          this._recursiveDirty();
        }
        get isAlignLeft() {
          return (this._alignFlags & 8) > 0;
        }
        set isAlignLeft(value) {
          this._setAlign(8, value);
          this._recursiveDirty();
        }
        get isAlignRight() {
          return (this._alignFlags & 32) > 0;
        }
        set isAlignRight(value) {
          this._setAlign(32, value);
          this._recursiveDirty();
        }
        get isAlignVerticalCenter() {
          return (this._alignFlags & 2) > 0;
        }
        set isAlignVerticalCenter(value) {
          if (value) {
            this.isAlignTop = false;
            this.isAlignBottom = false;
            this._alignFlags |= 2;
          } else {
            this._alignFlags &= ~2;
          }
          this._recursiveDirty();
        }
        get isAlignHorizontalCenter() {
          return (this._alignFlags & 16) > 0;
        }
        set isAlignHorizontalCenter(value) {
          if (value) {
            this.isAlignLeft = false;
            this.isAlignRight = false;
            this._alignFlags |= 16;
          } else {
            this._alignFlags &= ~16;
          }
          this._recursiveDirty();
        }
        get isStretchWidth() {
          return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
        }
        get isStretchHeight() {
          return (this._alignFlags & TOP_BOT) === TOP_BOT;
        }
        get top() {
          return this._top;
        }
        set top(value) {
          this._top = value;
          this._recursiveDirty();
        }
        get editorTop() {
          return this._isAbsTop ? this._top : this._top * 100;
        }
        set editorTop(value) {
          this._top = this._isAbsTop ? value : value / 100;
          this._recursiveDirty();
        }
        get bottom() {
          return this._bottom;
        }
        set bottom(value) {
          this._bottom = value;
          this._recursiveDirty();
        }
        get editorBottom() {
          return this._isAbsBottom ? this._bottom : this._bottom * 100;
        }
        set editorBottom(value) {
          this._bottom = this._isAbsBottom ? value : value / 100;
          this._recursiveDirty();
        }
        get left() {
          return this._left;
        }
        set left(value) {
          this._left = value;
          this._recursiveDirty();
        }
        get editorLeft() {
          return this._isAbsLeft ? this._left : this._left * 100;
        }
        set editorLeft(value) {
          this._left = this._isAbsLeft ? value : value / 100;
          this._recursiveDirty();
        }
        get right() {
          return this._right;
        }
        set right(value) {
          this._right = value;
          this._recursiveDirty();
        }
        get editorRight() {
          return this._isAbsRight ? this._right : this._right * 100;
        }
        set editorRight(value) {
          this._right = this._isAbsRight ? value : value / 100;
          this._recursiveDirty();
        }
        get horizontalCenter() {
          return this._horizontalCenter;
        }
        set horizontalCenter(value) {
          this._horizontalCenter = value;
          this._recursiveDirty();
        }
        get editorHorizontalCenter() {
          return this._isAbsHorizontalCenter ? this._horizontalCenter : this._horizontalCenter * 100;
        }
        set editorHorizontalCenter(value) {
          this._horizontalCenter = this._isAbsHorizontalCenter ? value : value / 100;
          this._recursiveDirty();
        }
        get verticalCenter() {
          return this._verticalCenter;
        }
        set verticalCenter(value) {
          this._verticalCenter = value;
          this._recursiveDirty();
        }
        get editorVerticalCenter() {
          return this._isAbsVerticalCenter ? this._verticalCenter : this._verticalCenter * 100;
        }
        set editorVerticalCenter(value) {
          this._verticalCenter = this._isAbsVerticalCenter ? value : value / 100;
          this._recursiveDirty();
        }
        get isAbsoluteTop() {
          return this._isAbsTop;
        }
        set isAbsoluteTop(value) {
          if (this._isAbsTop === value) {
            return;
          }
          this._isAbsTop = value;
          this._autoChangedValue(1, this._isAbsTop);
        }
        get isAbsoluteBottom() {
          return this._isAbsBottom;
        }
        set isAbsoluteBottom(value) {
          if (this._isAbsBottom === value) {
            return;
          }
          this._isAbsBottom = value;
          this._autoChangedValue(4, this._isAbsBottom);
        }
        get isAbsoluteLeft() {
          return this._isAbsLeft;
        }
        set isAbsoluteLeft(value) {
          if (this._isAbsLeft === value) {
            return;
          }
          this._isAbsLeft = value;
          this._autoChangedValue(8, this._isAbsLeft);
        }
        get isAbsoluteRight() {
          return this._isAbsRight;
        }
        set isAbsoluteRight(value) {
          if (this._isAbsRight === value) {
            return;
          }
          this._isAbsRight = value;
          this._autoChangedValue(32, this._isAbsRight);
        }
        get isAbsoluteHorizontalCenter() {
          return this._isAbsHorizontalCenter;
        }
        set isAbsoluteHorizontalCenter(value) {
          if (this._isAbsHorizontalCenter === value) {
            return;
          }
          this._isAbsHorizontalCenter = value;
          this._autoChangedValue(16, this._isAbsHorizontalCenter);
        }
        get isAbsoluteVerticalCenter() {
          return this._isAbsVerticalCenter;
        }
        set isAbsoluteVerticalCenter(value) {
          if (this._isAbsVerticalCenter === value) {
            return;
          }
          this._isAbsVerticalCenter = value;
          this._autoChangedValue(2, this._isAbsVerticalCenter);
        }
        get alignMode() {
          return this._alignMode;
        }
        set alignMode(value) {
          this._alignMode = value;
          this._recursiveDirty();
        }
        get alignFlags() {
          return this._alignFlags;
        }
        set alignFlags(value) {
          if (this._alignFlags === value) {
            return;
          }
          this._alignFlags = value;
          this._recursiveDirty();
        }
        updateAlignment() {
          cclegacy._widgetManager.updateAlignment(this.node);
        }
        _validateTargetInDEV() {
          {
            return;
          }
        }
        setDirty() {
          this._recursiveDirty();
        }
        onEnable() {
          this.node.getPosition(this._lastPos);
          this._lastSize.set(this.node._uiProps.uiTransformComp.contentSize);
          cclegacy._widgetManager.add(this);
          this._hadAlignOnce = false;
          this._registerEvent();
          this._registerTargetEvents();
        }
        onDisable() {
          cclegacy._widgetManager.remove(this);
          this._unregisterEvent();
          this._unregisterTargetEvents();
        }
        onDestroy() {
          this._removeParentEvent();
        }
        _adjustWidgetToAllowMovingInEditor(eventType) {}
        _adjustWidgetToAllowResizingInEditor() {}
        _adjustWidgetToAnchorChanged() {
          this.setDirty();
        }
        _adjustTargetToParentChanged(oldParent) {
          if (oldParent) {
            this._unregisterOldParentEvents(oldParent);
          }
          if (this.node.getParent()) {
            this._registerTargetEvents();
          }
          this._setDirtyByMode();
        }
        _registerEvent() {
          {
            this.node.on("transform-changed", this._setDirtyByMode, this);
            this.node.on("size-changed", this._setDirtyByMode, this);
          }
          this.node.on("anchor-changed", this._adjustWidgetToAnchorChanged, this);
          this.node.on("parent-changed", this._adjustTargetToParentChanged, this);
        }
        _unregisterEvent() {
          {
            this.node.off("transform-changed", this._setDirtyByMode, this);
            this.node.off("size-changed", this._setDirtyByMode, this);
          }
          this.node.off("anchor-changed", this._adjustWidgetToAnchorChanged, this);
        }
        _removeParentEvent() {
          this.node.off("parent-changed", this._adjustTargetToParentChanged, this);
        }
        _autoChangedValue(flag, isAbs) {
          const current = (this._alignFlags & flag) > 0;
          if (!current) {
            return;
          }
          const parentUiProps = this.node.parent && this.node.parent._uiProps;
          const parentTrans = parentUiProps && parentUiProps.uiTransformComp;
          const size = parentTrans ? parentTrans.contentSize : visibleRect;
          if (this.isAlignLeft && flag === 8) {
            this._left = isAbs ? this._left * size.width : this._left / size.width;
          } else if (this.isAlignRight && flag === 32) {
            this._right = isAbs ? this._right * size.width : this._right / size.width;
          } else if (this.isAlignHorizontalCenter && flag === 16) {
            this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width;
          } else if (this.isAlignTop && flag === 1) {
            this._top = isAbs ? this._top * size.height : this._top / size.height;
          } else if (this.isAlignBottom && flag === 4) {
            this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height;
          } else if (this.isAbsoluteVerticalCenter && flag === 2) {
            this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height;
          }
          this._recursiveDirty();
        }
        _registerTargetEvents() {
          const target = this._target || this.node.parent;
          if (target) {
            if (target.getComponent(UITransform)) {
              target.on("transform-changed", this._setDirtyByMode, this);
              target.on("size-changed", this._setDirtyByMode, this);
              target.on("anchor-changed", this._setDirtyByMode, this);
            }
          }
        }
        _unregisterTargetEvents() {
          const target = this._target || this.node.parent;
          if (target) {
            target.off("transform-changed", this._setDirtyByMode, this);
            target.off("size-changed", this._setDirtyByMode, this);
            target.off("anchor-changed", this._setDirtyByMode, this);
          }
        }
        _unregisterOldParentEvents(oldParent) {
          const target = this._target || oldParent;
          if (target) {
            target.off("transform-changed", this._setDirtyByMode, this);
            target.off("size-changed", this._setDirtyByMode, this);
          }
        }
        _setDirtyByMode() {
          if (this.alignMode === 1 || EDITOR_NOT_IN_PREVIEW) {
            this._recursiveDirty();
          }
        }
        _setAlign(flag, isAlign) {
          const current = (this._alignFlags & flag) > 0;
          if (isAlign === current) {
            return;
          }
          const isHorizontal = (flag & LEFT_RIGHT) > 0;
          const 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;
          }
        }
        _recursiveDirty() {
          if (this._dirty) {
            return;
          }
          this._dirty = true;
        }
      }, _class3$4.AlignMode = AlignMode, _class3$4), (_applyDecoratedDescriptor(_class2$8.prototype, "target", [_dec4$4], Object.getOwnPropertyDescriptor(_class2$8.prototype, "target"), _class2$8.prototype), _applyDecoratedDescriptor(_class2$8.prototype, "alignMode", [_dec5$4], Object.getOwnPropertyDescriptor(_class2$8.prototype, "alignMode"), _class2$8.prototype), _initializer$8 = applyDecoratedInitializer(_class2$8.prototype, "_alignFlags", [serializable$l], function () {
        return 0;
      }), _initializer2$6 = applyDecoratedInitializer(_class2$8.prototype, "_target", [serializable$l], function () {
        return null;
      }), _initializer3$4 = applyDecoratedInitializer(_class2$8.prototype, "_left", [serializable$l], function () {
        return 0;
      }), _initializer4$4 = applyDecoratedInitializer(_class2$8.prototype, "_right", [serializable$l], function () {
        return 0;
      }), _initializer5$3 = applyDecoratedInitializer(_class2$8.prototype, "_top", [serializable$l], function () {
        return 0;
      }), _initializer6$2 = applyDecoratedInitializer(_class2$8.prototype, "_bottom", [serializable$l], function () {
        return 0;
      }), _initializer7$2 = applyDecoratedInitializer(_class2$8.prototype, "_horizontalCenter", [serializable$l], function () {
        return 0;
      }), _initializer8$2 = applyDecoratedInitializer(_class2$8.prototype, "_verticalCenter", [serializable$l], function () {
        return 0;
      }), _initializer9$2 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsLeft", [serializable$l], function () {
        return true;
      }), _initializer10$2 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsRight", [serializable$l], function () {
        return true;
      }), _initializer11$2 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsTop", [serializable$l], function () {
        return true;
      }), _initializer12$2 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsBottom", [serializable$l], function () {
        return true;
      }), _initializer13 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsHorizontalCenter", [serializable$l], function () {
        return true;
      }), _initializer14 = applyDecoratedInitializer(_class2$8.prototype, "_isAbsVerticalCenter", [serializable$l], function () {
        return true;
      }), _initializer15 = applyDecoratedInitializer(_class2$8.prototype, "_originalWidth", [serializable$l], function () {
        return 0;
      }), _initializer16 = applyDecoratedInitializer(_class2$8.prototype, "_originalHeight", [serializable$l], function () {
        return 0;
      }), _initializer17 = applyDecoratedInitializer(_class2$8.prototype, "_alignMode", [serializable$l], function () {
        return 2;
      }), _initializer18 = applyDecoratedInitializer(_class2$8.prototype, "_lockFlags", [serializable$l, editorOnly], function () {
        return 0;
      })), _class2$8)) || _class$a) || _class$a) || _class$a); exports({ Widget: Widget, WidgetComponent: Widget });
      cclegacy.internal.computeInverseTransForTarget = computeInverseTransForTarget;
      cclegacy.internal.getReadonlyNodeSize = getReadonlyNodeSize;
      cclegacy.Widget = Widget;

      var _dec$9, _dec2$6, _dec3$6, _dec4$3, _dec5$3, _class$9, _class2$7, _initializer$7, _initializer2$5, _initializer3$3, _initializer4$3, _class3$3;
      const _color = new Color$1();
      const Direction = {
        "HORIZONTAL": 0,
        "VERTICAL": 1
      };
      ccenum(Direction);
      let PageViewIndicator = (_dec$9 = ccclass$H('cc.PageViewIndicator'), _dec2$6 = executionOrder$1(110), _dec3$6 = type$a(SpriteFrame), _dec4$3 = type$a(Direction), _dec5$3 = type$a(Size$1), _dec$9(_class$9 = _dec2$6(_class$9 = (_class2$7 = (_class3$3 = class PageViewIndicator extends Component {
        get spriteFrame() {
          return this._spriteFrame;
        }
        set spriteFrame(value) {
          if (this._spriteFrame === value) {
            return;
          }
          this._spriteFrame = value;
        }
        get direction() {
          return this._direction;
        }
        set direction(value) {
          if (this._direction === value) {
            return;
          }
          this._direction = value;
        }
        get cellSize() {
          return this._cellSize;
        }
        set cellSize(value) {
          if (this._cellSize === value) {
            return;
          }
          this._cellSize = value;
        }
        constructor() {
          super();
          this.spacing = _initializer$7 && _initializer$7();
          this._spriteFrame = _initializer2$5 && _initializer2$5();
          this._direction = _initializer3$3 && _initializer3$3();
          this._cellSize = _initializer4$3 && _initializer4$3();
          this._layout = null;
          this._pageView = null;
          this._indicators = [];
        }
        onLoad() {
          this._updateLayout();
        }
        setPageView(target) {
          this._pageView = target;
          this._refresh();
        }
        _updateLayout() {
          this._layout = this.getComponent(Layout);
          if (!this._layout) {
            this._layout = this.addComponent(Layout);
          }
          const layout = this._layout;
          if (this.direction === 0) {
            layout.type = 1;
            layout.spacingX = this.spacing;
          } else if (this.direction === 1) {
            layout.type = 2;
            layout.spacingY = this.spacing;
          }
          layout.resizeMode = 1;
        }
        _createIndicator() {
          const node = new Node$1();
          node.layer = this.node.layer;
          const 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;
        }
        _changedState() {
          const indicators = this._indicators;
          if (indicators.length === 0 || !this._pageView) {
            return;
          }
          const idx = this._pageView.curPageIdx;
          if (idx >= indicators.length) {
            return;
          }
          for (let i = 0; i < indicators.length; ++i) {
            const node = indicators[i];
            if (!node._uiProps.uiComp) {
              continue;
            }
            const uiComp = node._uiProps.uiComp;
            _color.set(uiComp.color);
            _color.a = 255 / 2;
            uiComp.color = _color;
          }
          if (indicators[idx]._uiProps.uiComp) {
            const comp = indicators[idx]._uiProps.uiComp;
            _color.set(comp.color);
            _color.a = 255;
            comp.color = _color;
          }
        }
        _refresh() {
          if (!this._pageView) {
            return;
          }
          const indicators = this._indicators;
          const pages = this._pageView.getPages();
          if (pages.length === indicators.length) {
            return;
          }
          let i = 0;
          if (pages.length > indicators.length) {
            for (i = 0; i < pages.length; ++i) {
              if (!indicators[i]) {
                indicators[i] = this._createIndicator();
              }
            }
          } else {
            const count = indicators.length - pages.length;
            for (i = count; i > 0; --i) {
              const node = indicators[i - 1];
              this.node.removeChild(node);
              indicators.splice(i - 1, 1);
            }
          }
          if (this._layout && this._layout.enabledInHierarchy) {
            this._layout.updateLayout();
          }
          this._changedState();
        }
      }, _class3$3.Direction = Direction, _class3$3), (_applyDecoratedDescriptor(_class2$7.prototype, "spriteFrame", [_dec3$6], Object.getOwnPropertyDescriptor(_class2$7.prototype, "spriteFrame"), _class2$7.prototype), _applyDecoratedDescriptor(_class2$7.prototype, "direction", [_dec4$3], Object.getOwnPropertyDescriptor(_class2$7.prototype, "direction"), _class2$7.prototype), _applyDecoratedDescriptor(_class2$7.prototype, "cellSize", [_dec5$3], Object.getOwnPropertyDescriptor(_class2$7.prototype, "cellSize"), _class2$7.prototype), _initializer$7 = applyDecoratedInitializer(_class2$7.prototype, "spacing", [serializable$l], function () {
        return 0;
      }), _initializer2$5 = applyDecoratedInitializer(_class2$7.prototype, "_spriteFrame", [serializable$l], function () {
        return null;
      }), _initializer3$3 = applyDecoratedInitializer(_class2$7.prototype, "_direction", [serializable$l], function () {
        return 0;
      }), _initializer4$3 = applyDecoratedInitializer(_class2$7.prototype, "_cellSize", [serializable$l], function () {
        return new Size$1(20, 20);
      })), _class2$7)) || _class$9) || _class$9); exports({ PageViewIndicator: PageViewIndicator, PageViewIndicatorComponent: PageViewIndicator });
      legacyCC.PageViewIndicator = PageViewIndicator;

      var _dec$8, _dec2$5, _dec3$5, _dec4$2, _dec5$2, _dec6$1, _dec7, _dec8, _dec9, _class$8, _class2$6, _initializer$6, _initializer2$4, _initializer3$2, _initializer4$2, _initializer5$2, _initializer6$1, _initializer7$1, _initializer8$1, _initializer9$1, _initializer10$1, _initializer11$1, _initializer12$1, _class3$2;
      const _tempVec2 = new Vec2();
      const SizeMode = {
        "Unified": 0,
        "Free": 1
      };
      ccenum(SizeMode);
      const PageViewDirection = {
        "HORIZONTAL": 0,
        "VERTICAL": 1
      };
      ccenum(PageViewDirection);
      const PageViewEventType = {
        "PAGE_TURNING": "page-turning"
      };
      let PageView = (_dec$8 = ccclass$H('cc.PageView'), _dec2$5 = executionOrder$1(110), _dec3$5 = type$a(SizeMode), _dec4$2 = type$a(PageViewDirection), _dec5$2 = type$a(PageViewIndicator), _dec6$1 = type$a(ScrollBar), _dec7 = type$a(ScrollBar), _dec8 = type$a([EventHandler]), _dec9 = type$a([EventHandler]), _dec$8(_class$8 = _dec2$5(_class$8 = (_class2$6 = (_class3$2 = class PageView extends ScrollView {
        get sizeMode() {
          return this._sizeMode;
        }
        set sizeMode(value) {
          if (this._sizeMode === value) {
            return;
          }
          this._sizeMode = value;
          this._syncSizeMode();
        }
        get direction() {
          return this._direction;
        }
        set direction(value) {
          if (this._direction === value) {
            return;
          }
          this._direction = value;
          this._syncScrollDirection();
        }
        get scrollThreshold() {
          return this._scrollThreshold;
        }
        set scrollThreshold(value) {
          if (this._scrollThreshold === value) {
            return;
          }
          this._scrollThreshold = value;
        }
        get pageTurningEventTiming() {
          return this._pageTurningEventTiming;
        }
        set pageTurningEventTiming(value) {
          if (this._pageTurningEventTiming === value) {
            return;
          }
          this._pageTurningEventTiming = value;
        }
        get indicator() {
          return this._indicator;
        }
        set indicator(value) {
          if (this._indicator === value) {
            return;
          }
          this._indicator = value;
          if (this.indicator) {
            this.indicator.setPageView(this);
          }
        }
        get curPageIdx() {
          return this._curPageIdx;
        }
        get verticalScrollBar() {
          return super.verticalScrollBar;
        }
        set verticalScrollBar(value) {
          super.verticalScrollBar = value;
        }
        get horizontalScrollBar() {
          return super.horizontalScrollBar;
        }
        set horizontalScrollBar(value) {
          super.horizontalScrollBar = value;
        }
        constructor() {
          super();
          this.autoPageTurningThreshold = _initializer$6 && _initializer$6();
          this.horizontal = _initializer2$4 && _initializer2$4();
          this.vertical = _initializer3$2 && _initializer3$2();
          this.cancelInnerEvents = _initializer4$2 && _initializer4$2();
          this.scrollEvents = _initializer5$2 && _initializer5$2();
          this.pageTurningSpeed = _initializer6$1 && _initializer6$1();
          this.pageEvents = _initializer7$1 && _initializer7$1();
          this._sizeMode = _initializer8$1 && _initializer8$1();
          this._direction = _initializer9$1 && _initializer9$1();
          this._scrollThreshold = _initializer10$1 && _initializer10$1();
          this._pageTurningEventTiming = _initializer11$1 && _initializer11$1();
          this._indicator = _initializer12$1 && _initializer12$1();
          this._curPageIdx = 0;
          this._lastPageIdx = 0;
          this._pages = [];
          this._initContentPos = v3();
          this._scrollCenterOffsetX = [];
          this._scrollCenterOffsetY = [];
          this._touchBeganPosition = v2$1();
          this._touchEndPosition = v2$1();
        }
        onEnable() {
          super.onEnable();
          this.node.on("size-changed", this._updateAllPagesSize, this);
          {
            this.node.on(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        }
        onDisable() {
          super.onDisable();
          this.node.off("size-changed", this._updateAllPagesSize, this);
          {
            this.node.off(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        }
        onLoad() {
          this._initPages();
          if (this.indicator) {
            this.indicator.setPageView(this);
          }
        }
        getCurrentPageIndex() {
          return this._curPageIdx;
        }
        setCurrentPageIndex(index) {
          this.scrollToPage(index, 1);
        }
        getPages() {
          return this._pages;
        }
        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();
        }
        insertPage(page, index) {
          if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) {
            return;
          }
          const 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();
          }
        }
        removePage(page) {
          if (!page || !this.content) {
            return;
          }
          const index = this._pages.indexOf(page);
          if (index === -1) {
            warnID(4300, page.name);
            return;
          }
          this.removePageAtIndex(index);
        }
        removePageAtIndex(index) {
          const pageList = this._pages;
          if (index < 0 || index >= pageList.length) {
            return;
          }
          const page = pageList[index];
          if (!page || !this.content) {
            return;
          }
          this.content.removeChild(page);
          pageList.splice(index, 1);
          this._updatePageView();
        }
        removeAllPages() {
          if (!this.content) {
            return;
          }
          const locPages = this._pages;
          for (let i = 0, len = locPages.length; i < len; i++) {
            this.content.removeChild(locPages[i]);
          }
          this._pages.length = 0;
          this._updatePageView();
        }
        scrollToPage(idx, 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();
          }
        }
        getScrollEndedEventTiming() {
          return this.pageTurningEventTiming;
        }
        _updatePageView() {
          if (!this.content) {
            return;
          }
          const layout = this.content.getComponent(Layout);
          if (layout && layout.enabled) {
            layout.updateLayout();
          }
          const pageCount = this._pages.length;
          if (this._curPageIdx >= pageCount) {
            this._curPageIdx = pageCount === 0 ? 0 : pageCount - 1;
            this._lastPageIdx = this._curPageIdx;
          }
          const contentPos = this._initContentPos;
          for (let i = 0; i < pageCount; ++i) {
            const page = this._pages[i];
            const pos = page.position;
            if (this.direction === 0) {
              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();
          }
        }
        _updateAllPagesSize() {
          const viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          if (this._sizeMode !== 0) {
            return;
          }
          const locPages = this._pages;
          const selfSize = viewTrans.contentSize;
          for (let i = 0, len = locPages.length; i < len; i++) {
            locPages[i]._uiProps.uiTransformComp.setContentSize(selfSize);
          }
        }
        _handleReleaseLogic() {
          this._autoScrollToPage();
          if (this._scrolling) {
            this._scrolling = false;
            if (!this._autoScrolling) {
              this._dispatchEvent(PageView.EventType.SCROLL_ENDED);
            }
          }
        }
        _onTouchBegan(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchBeganPosition, _tempVec2.x, _tempVec2.y);
          super._onTouchBegan(event, captureListeners);
        }
        _onTouchMoved(event, captureListeners) {
          super._onTouchMoved(event, captureListeners);
        }
        _onTouchEnded(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          super._onTouchEnded(event, captureListeners);
        }
        _onTouchCancelled(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          super._onTouchCancelled(event, captureListeners);
        }
        _onMouseWheel() {}
        _syncScrollDirection() {
          this.horizontal = this.direction === 0;
          this.vertical = this.direction === 1;
        }
        _syncSizeMode() {
          const viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          const layout = this.content.getComponent(Layout);
          if (layout) {
            if (this._sizeMode === 1 && this._pages.length > 0) {
              const firstPageTrans = this._pages[0]._uiProps.uiTransformComp;
              const lastPageTrans = this._pages[this._pages.length - 1]._uiProps.uiTransformComp;
              if (this.direction === 0) {
                layout.paddingLeft = (viewTrans.width - firstPageTrans.width) / 2;
                layout.paddingRight = (viewTrans.width - lastPageTrans.width) / 2;
              } else if (this.direction === 1) {
                layout.paddingTop = (viewTrans.height - firstPageTrans.height) / 2;
                layout.paddingBottom = (viewTrans.height - lastPageTrans.height) / 2;
              }
            }
            layout.updateLayout();
          }
        }
        _initPages() {
          if (!this.content) {
            return;
          }
          this._initContentPos = this.content.position;
          const children = this.content.children;
          for (let i = 0; i < children.length; ++i) {
            const page = children[i];
            if (this._pages.indexOf(page) >= 0) {
              continue;
            }
            this._pages.push(page);
          }
          this._syncScrollDirection();
          this._syncSizeMode();
          this._updatePageView();
        }
        _dispatchPageTurningEvent() {
          if (this._lastPageIdx === this._curPageIdx) {
            return;
          }
          this._lastPageIdx = this._curPageIdx;
          EventHandler.emitEvents(this.pageEvents, this, "page-turning");
          this.node.emit("page-turning", this);
        }
        _isQuicklyScrollable(touchMoveVelocity) {
          if (this.direction === 0) {
            if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) {
              return true;
            }
          } else if (this.direction === 1) {
            if (Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) {
              return true;
            }
          }
          return false;
        }
        _moveOffsetValue(idx) {
          const offset = new Vec2();
          if (this._sizeMode === 1) {
            if (this.direction === 0) {
              offset.x = this._scrollCenterOffsetX[idx];
            } else if (this.direction === 1) {
              offset.y = this._scrollCenterOffsetY[idx];
            }
          } else {
            const viewTrans = this.view;
            if (!viewTrans) {
              return offset;
            }
            if (this.direction === 0) {
              offset.x = idx * viewTrans.width;
            } else if (this.direction === 1) {
              offset.y = idx * viewTrans.height;
            }
          }
          return offset;
        }
        _getDragDirection(moveOffset) {
          if (this._direction === 0) {
            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;
          }
        }
        _isScrollable(offset, index, nextIndex) {
          if (this._sizeMode === 1) {
            let curPageCenter = 0;
            let nextPageCenter = 0;
            if (this.direction === 0) {
              curPageCenter = this._scrollCenterOffsetX[index];
              nextPageCenter = this._scrollCenterOffsetX[nextIndex];
              return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            } else if (this.direction === 1) {
              curPageCenter = this._scrollCenterOffsetY[index];
              nextPageCenter = this._scrollCenterOffsetY[nextIndex];
              return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            }
          } else {
            const viewTrans = this.view;
            if (!viewTrans) {
              return false;
            }
            if (this.direction === 0) {
              return Math.abs(offset.x) >= viewTrans.width * this.scrollThreshold;
            } else if (this.direction === 1) {
              return Math.abs(offset.y) >= viewTrans.height * this.scrollThreshold;
            }
          }
          return false;
        }
        _autoScrollToPage() {
          const bounceBackStarted = this._startBounceBackIfNeeded();
          if (bounceBackStarted) {
            const 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 {
            const moveOffset = new Vec2();
            Vec2.subtract(moveOffset, this._touchBeganPosition, this._touchEndPosition);
            const index = this._curPageIdx;
            const nextIndex = index + this._getDragDirection(moveOffset);
            const timeInSecond = this.pageTurningSpeed * Math.abs(index - nextIndex);
            if (nextIndex < this._pages.length) {
              if (this._isScrollable(moveOffset, index, nextIndex)) {
                this.scrollToPage(nextIndex, timeInSecond);
                return;
              } else {
                const touchMoveVelocity = this._calculateTouchMoveVelocity();
                if (this._isQuicklyScrollable(touchMoveVelocity)) {
                  this.scrollToPage(nextIndex, timeInSecond);
                  return;
                }
              }
            }
            this.scrollToPage(index, timeInSecond);
          }
        }
      }, _class3$2.SizeMode = SizeMode, _class3$2.Direction = PageViewDirection, _class3$2.EventType = extendsEnum(PageViewEventType, ScrollViewEventType), _class3$2), (_applyDecoratedDescriptor(_class2$6.prototype, "sizeMode", [_dec3$5], Object.getOwnPropertyDescriptor(_class2$6.prototype, "sizeMode"), _class2$6.prototype), _applyDecoratedDescriptor(_class2$6.prototype, "direction", [_dec4$2], Object.getOwnPropertyDescriptor(_class2$6.prototype, "direction"), _class2$6.prototype), _applyDecoratedDescriptor(_class2$6.prototype, "indicator", [_dec5$2], Object.getOwnPropertyDescriptor(_class2$6.prototype, "indicator"), _class2$6.prototype), _initializer$6 = applyDecoratedInitializer(_class2$6.prototype, "autoPageTurningThreshold", [serializable$l], function () {
        return 100;
      }), _applyDecoratedDescriptor(_class2$6.prototype, "verticalScrollBar", [_dec6$1, override$1], Object.getOwnPropertyDescriptor(_class2$6.prototype, "verticalScrollBar"), _class2$6.prototype), _applyDecoratedDescriptor(_class2$6.prototype, "horizontalScrollBar", [_dec7, override$1], Object.getOwnPropertyDescriptor(_class2$6.prototype, "horizontalScrollBar"), _class2$6.prototype), _initializer2$4 = applyDecoratedInitializer(_class2$6.prototype, "horizontal", [override$1, serializable$l], function () {
        return true;
      }), _initializer3$2 = applyDecoratedInitializer(_class2$6.prototype, "vertical", [override$1, serializable$l], function () {
        return true;
      }), _initializer4$2 = applyDecoratedInitializer(_class2$6.prototype, "cancelInnerEvents", [override$1, serializable$l], function () {
        return true;
      }), _initializer5$2 = applyDecoratedInitializer(_class2$6.prototype, "scrollEvents", [_dec8, serializable$l, override$1], function () {
        return [];
      }), _initializer6$1 = applyDecoratedInitializer(_class2$6.prototype, "pageTurningSpeed", [serializable$l], function () {
        return 0.3;
      }), _initializer7$1 = applyDecoratedInitializer(_class2$6.prototype, "pageEvents", [_dec9, serializable$l], function () {
        return [];
      }), _initializer8$1 = applyDecoratedInitializer(_class2$6.prototype, "_sizeMode", [serializable$l], function () {
        return 0;
      }), _initializer9$1 = applyDecoratedInitializer(_class2$6.prototype, "_direction", [serializable$l], function () {
        return 0;
      }), _initializer10$1 = applyDecoratedInitializer(_class2$6.prototype, "_scrollThreshold", [serializable$l], function () {
        return 0.5;
      }), _initializer11$1 = applyDecoratedInitializer(_class2$6.prototype, "_pageTurningEventTiming", [serializable$l], function () {
        return 0.1;
      }), _initializer12$1 = applyDecoratedInitializer(_class2$6.prototype, "_indicator", [serializable$l], function () {
        return null;
      })), _class2$6)) || _class$8) || _class$8); exports({ PageView: PageView, PageViewComponent: PageView });
      legacyCC.PageView = PageView;

      const _tempPos = new Vec3();
      const _defaultAnchor = new Vec2();
      const tInverseTranslate = new Vec2();
      const tInverseScale = new Vec2(1, 1);
      const _tempVec2_1 = new Vec2();
      const _tempVec2_2 = new Vec2();
      function align(node, widget) {
        if (widget._hadAlignOnce) return;
        if (widget.alignMode === 0) {
          widget._hadAlignOnce = true;
        }
        const hasTarget = widget.target;
        let target;
        const inverseTranslate = tInverseTranslate;
        const inverseScale = tInverseScale;
        if (hasTarget) {
          target = hasTarget;
          computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
        } else {
          target = node.parent;
        }
        const targetSize = getReadonlyNodeSize(target);
        const useGlobal = target instanceof Scene || !target.getComponent(UITransform);
        const targetAnchor = useGlobal ? _defaultAnchor : target.getComponent(UITransform).anchorPoint;
        const isRoot = useGlobal;
        node.getPosition(_tempPos);
        const uiTrans = node._uiProps.uiTransformComp;
        let x = _tempPos.x;
        let y = _tempPos.y;
        const anchor = uiTrans.anchorPoint;
        const scale = node.scale;
        if (widget.alignFlags & 56) {
          let localLeft = 0;
          let localRight = 0;
          const 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;
          }
          let width = 0;
          let anchorX = anchor.x;
          let 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) {
              let localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? widget.horizontalCenter : widget.horizontalCenter * targetWidth;
              let 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$2)) {
              width /= scaleX;
            } else {
              width = uiTrans.width;
            }
          }
          widget._lastSize.width = width;
        }
        if (widget.alignFlags & 7) {
          let localTop = 0;
          let localBottom = 0;
          const 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;
          }
          let height = 0;
          let anchorY = anchor.y;
          let 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) {
              let localVerticalCenter = widget.isAbsoluteVerticalCenter ? widget.verticalCenter : widget.verticalCenter * targetHeight;
              let 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$2)) {
              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) {
        const widget = node.getComponent(Widget);
        if (widget && widget.enabled) {
          if (!cclegacy.isValid(node, true)) {
            return;
          }
          activeWidgets.push(widget);
        }
        const children = node.children;
        for (const child of children) {
          if (child.active) {
            visitNode(child);
          }
        }
      }
      function refreshScene() {
        const scene = director.getScene();
        if (scene) {
          widgetManager.isAligning = true;
          if (widgetManager._nodesOrderDirty) {
            activeWidgets.length = 0;
            visitNode(scene);
            widgetManager._nodesOrderDirty = false;
          }
          let widget = null;
          const 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;
        }
      }
      const activeWidgets = [];
      function updateAlignment(node) {
        const parent = node.parent;
        if (parent && Node$1.isNode(parent)) {
          updateAlignment(parent);
        }
        const widget = node.getComponent(Widget);
        if (widget && parent) {
          align(node, widget);
        }
      }
      const widgetManager = exports("widgetManager", cclegacy._widgetManager = {
        isAligning: false,
        _nodesOrderDirty: false,
        _activeWidgetsIterator: new MutableForwardIterator(activeWidgets),
        animationState: null,
        init() {
          director.on("director_after_scene_launch", refreshScene);
          director.on("director_after_update", refreshScene);
          View.instance.on('design-resolution-changed', this.onResized, this);
          {
            const thisOnResized = this.onResized.bind(this);
            View.instance.on('canvas-resize', thisOnResized);
            screenAdapter.on('window-resize', thisOnResized);
          }
        },
        add(widget) {
          this._nodesOrderDirty = true;
        },
        remove(widget) {
          this._activeWidgetsIterator.remove(widget);
        },
        onResized() {
          const scene = director.getScene();
          if (scene) {
            this.refreshWidgetOnResized(scene);
          }
        },
        refreshWidgetOnResized(node) {
          const widget = Node$1.isNode(node) && node.getComponent(Widget);
          if (widget && widget.enabled && (widget.alignMode === 2 || widget.alignMode === 1)) {
            widget.setDirty();
          }
          const children = node.children;
          for (const child of children) {
            this.refreshWidgetOnResized(child);
          }
        },
        updateOffsetsToStayPut(widget, e) {
          function i(t, c) {
            return Math.abs(t - c) > 1e-10 ? c : t;
          }
          const widgetNode = widget.node;
          let widgetParent = widgetNode.parent;
          if (widgetParent) {
            const zero = _tempVec2_1;
            zero.set(0, 0);
            const one = _tempVec2_2;
            one.set(1, 1);
            if (widget.target) {
              widgetParent = widget.target;
              computeInverseTransForTarget(widgetNode, widgetParent, zero, one);
            }
            if (!e) {
              return;
            }
            const parentTrans = widgetParent._uiProps && widgetParent._uiProps.uiTransformComp;
            const parentAP = parentTrans ? parentTrans.anchorPoint : _defaultAnchor;
            const trans = widgetNode._uiProps.uiTransformComp;
            const matchSize = getReadonlyNodeSize(widgetParent);
            const myAP = trans.anchorPoint;
            const pos = widgetNode.position;
            const alignFlags = AlignFlags;
            const widgetNodeScale = widgetNode.scale;
            let temp = 0;
            if (e & alignFlags.LEFT) {
              let 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) {
              let 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) {
              let 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) {
              let 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,
        AlignMode,
        AlignFlags
      });
      director.on("director_init", () => {
        widgetManager.init();
      });

      var _dec$7, _dec2$4, _dec3$4, _class$7, _class2$5, _initializer$5;
      let SafeArea = (_dec$7 = ccclass$H('cc.SafeArea'), _dec2$4 = executionOrder$1(110), _dec3$4 = requireComponent(Widget), _dec$7(_class$7 = _dec2$4(_class$7 = _dec3$4(_class$7 = (_class2$5 = class SafeArea extends Component {
        get symmetric() {
          return this._symmetric;
        }
        set symmetric(value) {
          this._symmetric = value;
        }
        constructor() {
          super();
          this._symmetric = _initializer$5 && _initializer$5();
        }
        onEnable() {
          this.updateArea();
          screenAdapter.on('window-resize', this.updateArea, this);
          screenAdapter.on('orientation-change', this.updateArea, this);
        }
        onDisable() {
          screenAdapter.off('window-resize', this.updateArea, this);
          screenAdapter.off('orientation-change', this.updateArea, this);
        }
        updateArea() {
          const widget = this.node.getComponent(Widget);
          const uiTransComp = this.node.getComponent(UITransform);
          if (!widget || !uiTransComp) {
            return;
          }
          widget.updateAlignment();
          const lastPos = this.node.position.clone();
          const lastAnchorPoint = uiTransComp.anchorPoint.clone();
          widget.isAlignTop = widget.isAlignBottom = widget.isAlignLeft = widget.isAlignRight = true;
          const visibleSize = view.getVisibleSize();
          const screenWidth = visibleSize.width;
          const screenHeight = visibleSize.height;
          const safeArea = sys.getSafeAreaRect(this._symmetric);
          widget.top = screenHeight - safeArea.y - safeArea.height;
          widget.bottom = safeArea.y;
          widget.left = safeArea.x;
          widget.right = screenWidth - safeArea.x - safeArea.width;
          widget.updateAlignment();
          const curPos = this.node.position.clone();
          const anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width;
          const anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height;
          uiTransComp.setAnchorPoint(anchorX, anchorY);
          widgetManager.add(widget);
        }
      }, (_initializer$5 = applyDecoratedInitializer(_class2$5.prototype, "_symmetric", [serializable$l], function () {
        return true;
      })), _class2$5)) || _class$7) || _class$7) || _class$7); exports({ SafeArea: SafeArea, SafeAreaComponent: SafeArea });
      legacyCC.SafeArea = SafeArea;

      var _dec$6, _dec2$3, _dec3$3, _dec4$1, _dec5$1, _class$6, _class2$4, _initializer$4, _initializer2$3, _initializer3$1, _initializer4$1, _initializer5$1;
      let UICoordinateTracker = (_dec$6 = ccclass$H('cc.UICoordinateTracker'), _dec2$3 = executionOrder$1(110), _dec3$3 = type$a(Node$1), _dec4$1 = type$a(Camera), _dec5$1 = type$a([EventHandler]), _dec$6(_class$6 = _dec2$3(_class$6 = (_class2$4 = class UICoordinateTracker extends Component {
        get target() {
          return this._target;
        }
        set target(value) {
          if (this._target === value) {
            return;
          }
          this._target = value;
          this._checkCanMove();
        }
        get camera() {
          return this._camera;
        }
        set camera(value) {
          if (this._camera === value) {
            return;
          }
          this._camera = value;
          this._checkCanMove();
        }
        get useScale() {
          return this._useScale;
        }
        set useScale(value) {
          if (this._useScale === value) {
            return;
          }
          this._useScale = value;
        }
        get distance() {
          return this._distance;
        }
        set distance(value) {
          if (this._distance === value) {
            return;
          }
          this._distance = value;
        }
        constructor() {
          super();
          this.syncEvents = _initializer$4 && _initializer$4();
          this._target = _initializer2$3 && _initializer2$3();
          this._camera = _initializer3$1 && _initializer3$1();
          this._useScale = _initializer4$1 && _initializer4$1();
          this._distance = _initializer5$1 && _initializer5$1();
          this._transformPos = v3();
          this._viewPos = v3();
          this._canMove = true;
          this._lastWPos = v3();
          this._lastCameraPos = v3();
        }
        onEnable() {
          this._checkCanMove();
        }
        update() {
          const wPos = this.node.worldPosition;
          const 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) {
            const data = this._distance / Math.abs(this._viewPos.z);
            EventHandler.emitEvents(this.syncEvents, this._transformPos, data);
          }
        }
        _checkCanMove() {
          this._canMove = !!(this._camera && this._target);
        }
      }, (_applyDecoratedDescriptor(_class2$4.prototype, "target", [_dec3$3], Object.getOwnPropertyDescriptor(_class2$4.prototype, "target"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "camera", [_dec4$1], Object.getOwnPropertyDescriptor(_class2$4.prototype, "camera"), _class2$4.prototype), _initializer$4 = applyDecoratedInitializer(_class2$4.prototype, "syncEvents", [_dec5$1, serializable$l], function () {
        return [];
      }), _initializer2$3 = applyDecoratedInitializer(_class2$4.prototype, "_target", [serializable$l], function () {
        return null;
      }), _initializer3$1 = applyDecoratedInitializer(_class2$4.prototype, "_camera", [serializable$l], function () {
        return null;
      }), _initializer4$1 = applyDecoratedInitializer(_class2$4.prototype, "_useScale", [serializable$l], function () {
        return true;
      }), _initializer5$1 = applyDecoratedInitializer(_class2$4.prototype, "_distance", [serializable$l], function () {
        return 1;
      })), _class2$4)) || _class$6) || _class$6); exports({ UICoordinateTracker: UICoordinateTracker, UICoordinateTrackerComponent: UICoordinateTracker });

      var _dec$5, _class$5;
      const BlockEvents = ["touch-start", "touch-end", "touch-move", "mouse-down", "mouse-move", "mouse-up", "mouse-enter", "mouse-leave", "mouse-wheel"];
      function stopPropagation(event) {
        event.propagationStopped = true;
      }
      let BlockInputEvents = (_dec$5 = ccclass$H('cc.BlockInputEvents'), _dec$5(_class$5 = class BlockInputEvents extends Component {
        onEnable() {
          for (let i = 0; i < BlockEvents.length; i++) {
            this.node.on(BlockEvents[i], stopPropagation, this);
          }
        }
        onDisable() {
          for (let i = 0; i < BlockEvents.length; i++) {
            this.node.off(BlockEvents[i], stopPropagation, this);
          }
        }
      }) || _class$5); exports({ BlockInputEvents: BlockInputEvents, BlockInputEventsComponent: BlockInputEvents });

      var _dec$4, _dec2$2, _dec3$2, _class$4, _class2$3, _initializer$3, _initializer2$2;
      let SubContextView = exports("SubContextView", (_dec$4 = ccclass$H('cc.SubContextView'), _dec2$2 = executionOrder$1(110), _dec3$2 = requireComponent(UITransform), _dec$4(_class$4 = _dec2$2(_class$4 = _dec3$2(_class$4 = (_class2$3 = class SubContextView extends Component {
        get designResolutionSize() {
          return this._designResolutionSize;
        }
        set designResolutionSize(value) {
          {
            return;
          }
        }
        get fps() {
          return this._fps;
        }
        set fps(value) {
          if (this._fps === value) {
            return;
          }
          this._fps = value;
          this._updateInterval = 1000 / value;
        }
        constructor() {
          super();
          this._fps = _initializer$3 && _initializer$3();
          this._sprite = null;
          this._imageAsset = new ImageAsset$1();
          this._texture = new Texture2D$1();
          this._updatedTime = 0;
          this._updateInterval = 0;
          this._openDataContext = null;
          this._content = new Node$1('content');
          this._designResolutionSize = _initializer2$2 && _initializer2$2();
          this._content.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
          this._updatedTime = performance.now();
        }
        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;
          }
        }
        onEnable() {
          this._registerNodeEvent();
        }
        onDisable() {
          this._unregisterNodeEvent();
        }
        _initSharedCanvas() {
          if (this._openDataContext) {
            const sharedCanvas = this._openDataContext.canvas;
            let designWidth = this._designResolutionSize.width;
            let designHeight = this._designResolutionSize.height;
            sharedCanvas.width = designWidth;
            sharedCanvas.height = designHeight;
          }
        }
        _initContentNode() {
          if (this._openDataContext) {
            const sharedCanvas = this._openDataContext.canvas;
            const 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 {
              const sp = new SpriteFrame();
              sp.texture = this._texture;
              this._sprite.spriteFrame = sp;
            }
            this._content.parent = this.node;
          }
        }
        _updateSubContextView() {
          if (!this._openDataContext) {
            return;
          }
          const nodeTrans = this.node.getComponent(UITransform);
          const contentTrans = this._content.getComponent(UITransform);
          const scaleX = nodeTrans.width / contentTrans.width;
          const scaleY = nodeTrans.height / contentTrans.height;
          const scale = scaleX > scaleY ? scaleY : scaleX;
          contentTrans.width *= scale;
          contentTrans.height *= scale;
          const viewportRect = view.getViewportRect();
          const box = contentTrans.getBoundingBoxToWorld();
          const visibleSize = view.getVisibleSize();
          const dpr = screenAdapter.devicePixelRatio;
          const x = (viewportRect.width * (box.x / visibleSize.width) + viewportRect.x) / dpr;
          const y = (viewportRect.height * (box.y / visibleSize.height) + viewportRect.y) / dpr;
          const width = viewportRect.width * (box.width / visibleSize.width) / dpr;
          const height = viewportRect.height * (box.height / visibleSize.height) / dpr;
          this._openDataContext.postMessage({
            fromEngine: true,
            type: 'engine',
            event: 'viewport',
            x,
            y,
            width,
            height
          });
        }
        _updateSubContextTexture() {
          const img = this._imageAsset;
          if (!img || !this._openDataContext) {
            return;
          }
          if (img.width <= 0 || img.height <= 0) {
            return;
          }
          const 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);
        }
        _registerNodeEvent() {
          this.node.on("transform-changed", this._updateSubContextView, this);
          this.node.on("size-changed", this._updateSubContextView, this);
          this.node.on("layer-changed", this._updateContentLayer, this);
        }
        _unregisterNodeEvent() {
          this.node.off("transform-changed", this._updateSubContextView, this);
          this.node.off("size-changed", this._updateSubContextView, this);
          this.node.off("layer-changed", this._updateContentLayer, this);
        }
        _updateContentLayer() {
          this._content.layer = this.node.layer;
        }
        update(dt) {
          const calledUpdateManually = dt === undefined;
          if (calledUpdateManually) {
            this._updateSubContextTexture();
            return;
          }
          const now = performance.now();
          const deltaTime = now - this._updatedTime;
          if (deltaTime >= this._updateInterval) {
            this._updatedTime += this._updateInterval;
            this._updateSubContextTexture();
          }
        }
        onDestroy() {
          this._content.destroy();
          this._texture.destroy();
          if (this._sprite) {
            this._sprite.destroy();
          }
          this._imageAsset.destroy();
          this._openDataContext = null;
        }
      }, (_initializer$3 = applyDecoratedInitializer(_class2$3.prototype, "_fps", [serializable$l], function () {
        return 60;
      }), _initializer2$2 = applyDecoratedInitializer(_class2$3.prototype, "_designResolutionSize", [serializable$l], function () {
        return new Size$1(640, 960);
      })), _class2$3)) || _class$4) || _class$4) || _class$4));
      legacyCC.SubContextView = SubContextView;

      deprecateModuleExportedName({
        ButtonComponent: {
          newName: 'Button',
          since: '1.2.0',
          removed: false
        },
        EditBoxComponent: {
          newName: 'EditBox',
          since: '1.2.0',
          removed: false
        },
        LayoutComponent: {
          newName: 'Layout',
          since: '1.2.0',
          removed: false
        },
        ProgressBarComponent: {
          newName: 'ProgressBar',
          since: '1.2.0',
          removed: false
        },
        ScrollViewComponent: {
          newName: 'ScrollView',
          since: '1.2.0',
          removed: false
        },
        ScrollBarComponent: {
          newName: 'ScrollBar',
          since: '1.2.0',
          removed: false
        },
        SliderComponent: {
          newName: 'Slider',
          since: '1.2.0',
          removed: false
        },
        ToggleComponent: {
          newName: 'Toggle',
          since: '1.2.0',
          removed: false
        },
        ToggleContainerComponent: {
          newName: 'ToggleContainer',
          since: '1.2.0',
          removed: false
        },
        WidgetComponent: {
          newName: 'Widget',
          since: '1.2.0',
          removed: false
        },
        PageViewComponent: {
          newName: 'PageView',
          since: '1.2.0',
          removed: false
        },
        PageViewIndicatorComponent: {
          newName: 'PageViewIndicator',
          since: '1.2.0',
          removed: false
        },
        SafeAreaComponent: {
          newName: 'SafeArea',
          since: '1.2.0',
          removed: false
        },
        UICoordinateTrackerComponent: {
          newName: 'UICoordinateTracker',
          since: '1.2.0',
          removed: false
        },
        BlockInputEventsComponent: {
          newName: 'BlockInputEvents',
          since: '1.2.0',
          removed: false
        }
      });

      var _dec$3, _class$3;
      let UIReorderComponent = exports("UIReorderComponent", (_dec$3 = ccclass$H('cc.UIReorderComponent'), _dec$3(_class$3 = class UIReorderComponent {
        constructor() {
          warnID(1408, 'UIReorderComponent');
        }
      }) || _class$3));
      legacyCC.UIReorderComponent = UIReorderComponent;
      legacyCC.ButtonComponent = Button;
      setClassAlias(Button, 'cc.ButtonComponent');
      legacyCC.EditBoxComponent = EditBox;
      setClassAlias(EditBox, 'cc.EditBoxComponent');
      legacyCC.LayoutComponent = Layout;
      setClassAlias(Layout, 'cc.LayoutComponent');
      legacyCC.ProgressBarComponent = ProgressBar;
      setClassAlias(ProgressBar, 'cc.ProgressBarComponent');
      legacyCC.ScrollViewComponent = ScrollView;
      setClassAlias(ScrollView, 'cc.ScrollViewComponent');
      legacyCC.ScrollBarComponent = ScrollBar;
      setClassAlias(ScrollBar, 'cc.ScrollBarComponent');
      legacyCC.SliderComponent = Slider;
      setClassAlias(Slider, 'cc.SliderComponent');
      legacyCC.ToggleComponent = Toggle;
      setClassAlias(Toggle, 'cc.ToggleComponent');
      legacyCC.ToggleContainerComponent = ToggleContainer;
      setClassAlias(ToggleContainer, 'cc.ToggleContainerComponent');
      legacyCC.WidgetComponent = Widget;
      setClassAlias(Widget, 'cc.WidgetComponent');
      legacyCC.PageViewComponent = PageView;
      setClassAlias(PageView, 'cc.PageViewComponent');
      legacyCC.PageViewIndicatorComponent = PageViewIndicator;
      setClassAlias(PageViewIndicator, 'cc.PageViewIndicatorComponent');
      legacyCC.SafeAreaComponent = SafeArea;
      setClassAlias(SafeArea, 'cc.SafeAreaComponent');
      setClassAlias(UICoordinateTracker, 'cc.UICoordinateTrackerComponent');
      legacyCC.BlockInputEventsComponent = BlockInputEvents;
      setClassAlias(BlockInputEvents, 'cc.BlockInputEventsComponent');
      removeProperty(View.prototype, 'View.prototype', [{
        name: 'isAntiAliasEnabled',
        suggest: 'The API of Texture2d have been largely modified, no alternative'
      }, {
        name: 'enableAntiAlias',
        suggest: 'The API of Texture2d have been largely modified, no alternative'
      }]);
      markAsWarning(View.prototype, 'View.prototype', [{
        name: 'adjustViewportMeta'
      }, {
        name: 'enableAutoFullScreen',
        suggest: 'use screen.requestFullScreen() instead.'
      }, {
        name: 'isAutoFullScreenEnabled'
      }, {
        name: 'setCanvasSize',
        suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'getCanvasSize',
        suggest: 'please use screen.windowSize instead.'
      }, {
        name: 'getFrameSize',
        suggest: 'getting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'setFrameSize',
        suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'getDevicePixelRatio',
        suggest: 'use screen.devicePixelRatio instead.'
      }, {
        name: 'convertToLocationInView'
      }, {
        name: 'enableRetina'
      }, {
        name: 'isRetinaEnabled'
      }, {
        name: 'setRealPixelResolution'
      }]);

      var _dec$2, _class$2, _class2$2, _initializer$2;
      let VideoClip = exports("VideoClip", (_dec$2 = ccclass$H('cc.VideoClip'), _dec$2(_class$2 = (_class2$2 = class VideoClip extends Asset {
        constructor() {
          super();
          this._duration = _initializer$2 && _initializer$2();
          this._video = null;
        }
        set _nativeAsset(clip) {
          this._video = clip;
          if (clip) {
            this._duration = clip.duration;
          } else {
            this._duration = 0;
          }
        }
        get _nativeAsset() {
          return this._video;
        }
      }, (_initializer$2 = applyDecoratedInitializer(_class2$2.prototype, "_duration", [serializable$l], function () {
        return 0;
      })), _class2$2)) || _class$2));

      const ccdocument$2 = ccwindow$1.document;
      function downloadVideo(url, options, onComplete) {
        const video = ccdocument$2.createElement('video');
        const source = ccdocument$2.createElement('source');
        video.appendChild(source);
        const req = new XMLHttpRequest();
        req.open('GET', url, true);
        req.responseType = 'blob';
        req.onload = function onload() {
          if (this.status === 200 || this.status === 0) {
            source.src = URL.createObjectURL(this.response);
            onComplete(null, video);
          } else {
            onComplete(new Error(`${req.status}(no response)`));
          }
        };
        req.onerror = function onerror() {
          const message = `load video failure - ${url}`;
          log(message);
          onComplete(new Error(message));
        };
        req.send();
      }
      function createVideoClip(id, data, options, onComplete) {
        const out = new VideoClip();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      downloader$1.register({
        '.mp4': downloadVideo,
        '.avi': downloadVideo,
        '.mov': downloadVideo,
        '.mpg': downloadVideo,
        '.mpeg': downloadVideo,
        '.rm': downloadVideo,
        '.rmvb': downloadVideo
      });
      factory.register({
        '.mp4': createVideoClip,
        '.avi': createVideoClip,
        '.mov': createVideoClip,
        '.mpg': createVideoClip,
        '.mpeg': createVideoClip,
        '.rm': createVideoClip,
        '.rmvb': createVideoClip
      });

      class VideoPlayerImpl {
        constructor(component) {
          this._componentEventList = new Map();
          this._state = "none";
          this._video = null;
          this._onInterruptedBegin = void 0;
          this._onInterruptedEnd = void 0;
          this._interrupted = false;
          this._loaded = false;
          this._loadedMeta = false;
          this._ignorePause = false;
          this._fullScreenOnAwake = false;
          this._visible = true;
          this._playing = false;
          this._cachedCurrentTime = -1;
          this._waitingFullscreen = false;
          this._waitingPlay = false;
          this._keepAspectRatio = false;
          this._component = null;
          this._uiTrans = null;
          this._node = null;
          this._stayOnBottom = false;
          this._dirty = false;
          this._forceUpdate = false;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._component = component;
          this._node = component.node;
          this._uiTrans = component.node.getComponent(UITransform);
          this._onInterruptedBegin = () => {
            if (!this.video || this._state !== "playing") {
              return;
            }
            this.video.pause();
            this._interrupted = true;
          };
          this._onInterruptedEnd = () => {
            if (!this._interrupted || !this.video) {
              return;
            }
            this.video.play();
            this._interrupted = false;
          };
          legacyCC.game.on(legacyCC.Game.EVENT_PAUSE, this._onInterruptedBegin);
          legacyCC.game.on(legacyCC.Game.EVENT_RESUME, this._onInterruptedEnd);
        }
        get fullScreenOnAwake() {
          return this._fullScreenOnAwake;
        }
        get loaded() {
          return this._loaded;
        }
        get componentEventList() {
          return this._componentEventList;
        }
        get video() {
          return this._video;
        }
        get state() {
          return this._state;
        }
        get isPlaying() {
          return this._playing;
        }
        get UICamera() {
          return director.root.batcher2D.getFirstRenderCamera(this._node);
        }
        onLoadedMetadata(e) {
          this._loadedMeta = true;
          this._forceUpdate = true;
          if (this._visible) {
            this.enable();
          } else {
            this.disable();
          }
          this.dispatchEvent("meta-loaded");
          const video = e.target;
          if (this._keepAspectRatio && video) {
            this.syncUITransform(video.videoWidth, video.videoHeight);
          }
          this.delayedFullScreen();
          this.delayedPlay();
        }
        onCanPlay(e) {
          this._loaded = true;
          this.dispatchEvent("ready-to-play");
        }
        onPlay(e) {
          this._playing = true;
          this.dispatchEvent("playing");
        }
        onPlaying(e) {
          this.dispatchEvent("playing");
        }
        onPause(e) {
          this._playing = false;
          if (this._ignorePause) {
            this._ignorePause = false;
            return;
          }
          this.dispatchEvent("paused");
        }
        onStoped(e) {
          this._playing = false;
          this._ignorePause = false;
          this.dispatchEvent("stopped");
        }
        onEnded(e) {
          this._playing = false;
          this.dispatchEvent("completed");
        }
        onClick(e) {
          this.dispatchEvent("clicked");
        }
        onError(e) {
          this.dispatchEvent("error");
          const video = e.target;
          if (video && video.error) {
            error(`Error ${video.error.code}; details: ${video.error.message}`);
          }
        }
        play() {
          if (this._loadedMeta || this._loaded) {
            this.canPlay();
          } else {
            this._waitingPlay = true;
          }
        }
        delayedPlay() {
          if (this._waitingPlay) {
            this.canPlay();
            this._waitingPlay = false;
          }
        }
        syncFullScreenOnAwake(enabled) {
          this._fullScreenOnAwake = enabled;
          if (this._loadedMeta || this._loaded) {
            this.canFullScreen(enabled);
          } else {
            this._waitingFullscreen = true;
          }
        }
        delayedFullScreen() {
          if (this._waitingFullscreen) {
            this.canFullScreen(this._fullScreenOnAwake);
            this._waitingFullscreen = false;
          }
        }
        dispatchEvent(key) {
          const callback = this._componentEventList.get(key);
          if (callback) {
            this._state = key;
            callback.call(this);
          }
        }
        syncUITransform(width, height) {
          if (this._uiTrans) {
            this._uiTrans.width = width;
            this._uiTrans.height = height;
          }
        }
        syncCurrentTime() {
          if (!this.video) {
            return;
          }
          if (this._cachedCurrentTime !== -1 && this.video.currentTime !== this._cachedCurrentTime) {
            this.seekTo(this._cachedCurrentTime);
            this._cachedCurrentTime = -1;
          }
        }
        destroy() {
          this.removeVideoPlayer();
          this._componentEventList.clear();
          legacyCC.game.off(legacyCC.Game.EVENT_PAUSE, this._onInterruptedBegin);
          legacyCC.game.off(legacyCC.Game.EVENT_RESUME, this._onInterruptedEnd);
        }
      }
      legacyCC.internal.VideoPlayerImpl = VideoPlayerImpl;

      const ccdocument$1 = ccwindow$1.document;
      const MIN_ZINDEX = -(2 ** 15);
      const _mat4_temp$1 = mat4();
      class VideoPlayerImplWeb extends VideoPlayerImpl {
        constructor(component) {
          super(component);
          this._eventList = new Map();
          this._clearColorA = -1;
          this._clearFlag = void 0;
        }
        addListener(type, handler) {
          if (!this._video) {
            return;
          }
          this._eventList.set(type, handler);
          this._video.addEventListener(type, handler);
        }
        removeAllListeners() {
          this._eventList.forEach((handler, type) => {
            if (!this._video) {
              return;
            }
            this._video.removeEventListener(type, handler);
          });
          this._eventList.clear();
        }
        canPlay() {
          if (this.video) {
            const promise = this.video.play();
            if (ccwindow$1.Promise && promise instanceof Promise) {
              promise.catch(error => {}).then(() => {
                this.syncCurrentTime();
              });
            }
          }
        }
        pause() {
          if (this.video) {
            this.video.pause();
            this._cachedCurrentTime = this.video.currentTime;
          }
        }
        resume() {
          this.play();
        }
        stop() {
          if (this.video) {
            this._ignorePause = true;
            this.video.currentTime = 0;
            this.video.pause();
            this._cachedCurrentTime = 0;
            setTimeout(() => {
              this._ignorePause = false;
              this.dispatchEvent("stopped");
            }, 0);
          }
        }
        syncClip(clip) {
          this.removeVideoPlayer();
          if (!clip) {
            return;
          }
          this.createVideoPlayer(clip.nativeUrl);
        }
        syncURL(url) {
          this.removeVideoPlayer();
          if (!url) {
            return;
          }
          this.createVideoPlayer(url);
        }
        syncPlaybackRate(val) {
          if (sys.browserType === BrowserType.UC) {
            warn('playbackRate is not supported by the uc mobile browser.');
            return;
          }
          if (this.video) {
            this.video.playbackRate = val;
          }
        }
        syncVolume(val) {
          if (this.video) {
            this.video.volume = val;
          }
        }
        syncMute(enabled) {
          if (this.video) {
            this.video.muted = enabled;
          }
        }
        syncLoop(enabled) {
          if (this.video) {
            this.video.loop = enabled;
          }
        }
        getDuration() {
          if (!this.video) {
            return 0;
          }
          return this.video.duration;
        }
        getCurrentTime() {
          if (this.video) {
            return this.video.currentTime;
          }
          return -1;
        }
        seekTo(val) {
          if (this.video) {
            this.video.currentTime = val;
            this._cachedCurrentTime = this.video.currentTime;
          }
        }
        canFullScreen(enabled) {
          const video = this._video;
          if (!video || video.readyState !== 4) {
            return;
          }
          if (sys.os === OS.IOS && sys.isBrowser) {
            if (enabled) {
              if (video.webkitEnterFullscreen) {
                video.webkitEnterFullscreen();
              }
            } else if (video.webkitExitFullscreen) {
              video.webkitExitFullscreen();
            }
            this._fullScreenOnAwake = video.webkitDisplayingFullscreen;
            return;
          }
          if (!screen.supportsFullScreen) {
            this._fullScreenOnAwake = enabled;
            this._forceUpdate = true;
            this.syncMatrix();
            return;
          }
          if (enabled) {
            if (sys.browserType === BrowserType.IE) {
              video.style.transform = '';
            }
            video.setAttribute('x5-video-player-fullscreen', 'true');
            screen.requestFullScreen(video, document => {
              const fullscreenElement = sys.browserType === BrowserType.IE ? document.msFullscreenElement : document.fullscreenElement;
              this._fullScreenOnAwake = fullscreenElement === video;
            }, () => {
              this._fullScreenOnAwake = false;
            });
          } else {
            video.removeAttribute('x5-video-player-fullscreen');
            screen.exitFullScreen();
          }
        }
        syncStayOnBottom(enabled) {
          if (this._video) {
            this._video.style['z-index'] = enabled ? MIN_ZINDEX : 0;
            this._stayOnBottom = enabled;
          }
          this._dirty = true;
        }
        syncKeepAspectRatio(enabled) {
          this._keepAspectRatio = enabled;
          if (enabled && this._loadedMeta && this._video) {
            this.syncUITransform(this._video.videoWidth, this._video.videoHeight);
          }
        }
        removeVideoPlayer() {
          const video = this._video;
          if (video) {
            if (contains$1(game.container, video)) {
              game.container.removeChild(video);
              this.removeAllListeners();
            }
          }
          this._cachedCurrentTime = 0;
          this._playing = false;
          this._loaded = false;
          this._loadedMeta = false;
          this._video = null;
        }
        createVideoPlayer(url) {
          const video = this._video = ccdocument$1.createElement('video');
          video.className = 'cocosVideo';
          video.style.visibility = 'hidden';
          video.style.position = 'absolute';
          video.style.bottom = '0px';
          video.style.left = '0px';
          video.style['transform-origin'] = '0px 100% 0px';
          video.style['-webkit-transform-origin'] = '0px 100% 0px';
          video.setAttribute('preload', 'auto');
          video.setAttribute('webkit-playsinline', '');
          video.setAttribute('x5-playsinline', '');
          video.setAttribute('playsinline', '');
          this._bindDomEvent();
          game.container.appendChild(video);
          const source = ccdocument$1.createElement('source');
          video.appendChild(source);
          source.src = url;
        }
        _bindDomEvent() {
          this._video;
          this.addListener('loadedmetadata', this.onLoadedMetadata.bind(this));
          this.addListener('canplay', this.onCanPlay.bind(this));
          this.addListener('canplaythrough', this.onCanPlay.bind(this));
          this.addListener('play', this.onPlay.bind(this));
          this.addListener('playing', this.onPlaying.bind(this));
          this.addListener('pause', this.onPause.bind(this));
          this.addListener('click', this.onClick.bind(this));
          this.addListener('ended', this.onEnded.bind(this));
          this.addListener('error', this.onError.bind(this));
        }
        onCanPlay(e) {
          const video = e.target;
          if (this._loaded && video) {
            return;
          }
          switch (video.readyState) {
            case 1:
            case 4:
              {
                super.onCanPlay(e);
                break;
              }
          }
        }
        enable() {
          if (this._video) {
            this._visible = true;
            if (this._video.style.visibility === 'visible') {
              return;
            }
            this._video.style.visibility = 'visible';
          }
        }
        disable(noPause) {
          if (this._video) {
            if (!noPause && this._playing) {
              this._video.pause();
            }
            this._visible = false;
            if (this._video.style.visibility === 'hidden') {
              return;
            }
            this._video.style.visibility = 'hidden';
          }
        }
        syncMatrix() {
          if (!this._video || !this._visible || !this._component) return;
          const camera = this.UICamera;
          if (!camera) {
            return;
          }
          if (screen.fullScreen()) {
            return;
          }
          if (this._dirty) {
            this._dirty = false;
            if (this._stayOnBottom) {
              this._clearColorA = camera.clearColor.w;
              this._clearFlag = camera.clearFlag;
              camera.clearColor.w = 0;
              camera.clearFlag = 7;
            } else if (this._clearFlag) {
              camera.clearColor.w = this._clearColorA;
              camera.clearFlag = this._clearFlag;
              this._clearColorA = -1;
              this._clearFlag = null;
            }
          }
          this._component.node.getWorldMatrix(_mat4_temp$1);
          camera.update(true);
          camera.worldMatrixToScreen(_mat4_temp$1, _mat4_temp$1, game.canvas.width, game.canvas.height);
          let width = 0;
          let height = 0;
          if (this._fullScreenOnAwake) {
            width = visibleRect.width;
            height = visibleRect.height;
          } else {
            width = this._uiTrans.contentSize.width;
            height = this._uiTrans.contentSize.height;
          }
          if (!this._forceUpdate && this._m00 === _mat4_temp$1.m00 && this._m01 === _mat4_temp$1.m01 && this._m04 === _mat4_temp$1.m04 && this._m05 === _mat4_temp$1.m05 && this._m12 === _mat4_temp$1.m12 && this._m13 === _mat4_temp$1.m13 && this._w === width && this._h === height) {
            return;
          }
          this._m00 = _mat4_temp$1.m00;
          this._m01 = _mat4_temp$1.m01;
          this._m04 = _mat4_temp$1.m04;
          this._m05 = _mat4_temp$1.m05;
          this._m12 = _mat4_temp$1.m12;
          this._m13 = _mat4_temp$1.m13;
          this._w = width;
          this._h = height;
          const dpr = screenAdapter.devicePixelRatio;
          const scaleX = 1 / dpr;
          const scaleY = 1 / dpr;
          const container = game.container;
          const sx = _mat4_temp$1.m00 * scaleX;
          const b = _mat4_temp$1.m01;
          const c = _mat4_temp$1.m04;
          const sy = _mat4_temp$1.m05 * scaleY;
          this._video.style.width = `${this._w}px`;
          this._video.style.height = `${this._h}px`;
          if (sys.browserType !== BrowserType.MOBILE_QQ) {
            this._video.style.objectFit = this._keepAspectRatio ? 'none' : 'fill';
          } else {
            warn('keepAspectRatio is not supported by the qq mobile browser.');
          }
          const w = this._w * scaleX;
          const h = this._h * scaleY;
          const {
            x,
            y
          } = this._uiTrans.anchorPoint;
          const appx = w * _mat4_temp$1.m00 * x;
          const appy = h * _mat4_temp$1.m05 * y;
          const offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
          const offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
          const tx = _mat4_temp$1.m12 * scaleX - appx + offsetX;
          const ty = _mat4_temp$1.m13 * scaleY - appy + offsetY;
          const matrix = `matrix(${sx},${-b},${-c},${sy},${tx},${-ty})`;
          this._video.style.transform = matrix;
          this._video.style['-webkit-transform'] = matrix;
          if (sys.browserType !== BrowserType.IE) {
            this._forceUpdate = false;
          }
        }
      }

      class VideoPlayerImplManager {
        static getImpl(component) {
          return new VideoPlayerImplWeb(component);
        }
      }
      legacyCC.internal.VideoPlayerImplManager = VideoPlayerImplManager;

      const ResourceType = Enum({
        REMOTE: 0,
        LOCAL: 1
      });
      const VideoPlayerEventType = {
        "NONE": "none",
        "PLAYING": "playing",
        "PAUSED": "paused",
        "STOPPED": "stopped",
        "COMPLETED": "completed",
        "META_LOADED": "meta-loaded",
        "READY_TO_PLAY": "ready-to-play",
        "ERROR": "error",
        "CLICKED": "clicked"
      };

      var _dec$1, _dec2$1, _dec3$1, _dec4, _dec5, _dec6, _class$1, _class2$1, _initializer$1, _initializer2$1, _initializer3, _initializer4, _initializer5, _initializer6, _initializer7, _initializer8, _initializer9, _initializer10, _initializer11, _initializer12, _class3$1;
      let VideoPlayer = exports("VideoPlayer", (_dec$1 = ccclass$H('cc.VideoPlayer'), _dec2$1 = requireComponent(UITransform), _dec3$1 = type$a(VideoClip), _dec4 = type$a(ResourceType), _dec5 = type$a(VideoClip), _dec6 = type$a([EventHandler]), _dec$1(_class$1 = _dec2$1(_class$1 = (_class2$1 = (_class3$1 = class VideoPlayer extends Component {
        constructor() {
          super();
          this._resourceType = _initializer$1 && _initializer$1();
          this._remoteURL = _initializer2$1 && _initializer2$1();
          this._clip = _initializer3 && _initializer3();
          this._playOnAwake = _initializer4 && _initializer4();
          this._volume = _initializer5 && _initializer5();
          this._mute = _initializer6 && _initializer6();
          this._playbackRate = _initializer7 && _initializer7();
          this._loop = _initializer8 && _initializer8();
          this._fullScreenOnAwake = _initializer9 && _initializer9();
          this._stayOnBottom = _initializer10 && _initializer10();
          this._keepAspectRatio = _initializer11 && _initializer11();
          this._impl = null;
          this._cachedCurrentTime = 0;
          this.videoPlayerEvent = _initializer12 && _initializer12();
        }
        get resourceType() {
          return this._resourceType;
        }
        set resourceType(val) {
          if (this._resourceType !== val) {
            this._resourceType = val;
            this.syncSource();
          }
        }
        get remoteURL() {
          return this._remoteURL;
        }
        set remoteURL(val) {
          if (this._remoteURL !== val) {
            this._remoteURL = val;
            this.syncSource();
          }
        }
        get clip() {
          return this._clip;
        }
        set clip(val) {
          if (this._clip !== val) {
            this._clip = val;
            this.syncSource();
          }
        }
        get playOnAwake() {
          return this._playOnAwake;
        }
        set playOnAwake(value) {
          this._playOnAwake = value;
        }
        get playbackRate() {
          return this._playbackRate;
        }
        set playbackRate(value) {
          this._playbackRate = value;
          if (this._impl) {
            this._impl.syncPlaybackRate(value);
          }
        }
        get volume() {
          return this._volume;
        }
        set volume(value) {
          this._volume = value;
          if (this._impl) {
            this._impl.syncVolume(value);
          }
        }
        get mute() {
          return this._mute;
        }
        set mute(value) {
          this._mute = value;
          if (this._impl) {
            this._impl.syncMute(value);
          }
        }
        get loop() {
          return this._loop;
        }
        set loop(value) {
          this._loop = value;
          if (this._impl) {
            this._impl.syncLoop(value);
          }
        }
        get keepAspectRatio() {
          return this._keepAspectRatio;
        }
        set keepAspectRatio(value) {
          if (this._keepAspectRatio !== value) {
            this._keepAspectRatio = value;
            if (this._impl) {
              this._impl.syncKeepAspectRatio(value);
            }
          }
        }
        get fullScreenOnAwake() {
          {
            if (this._impl) {
              this._fullScreenOnAwake = this._impl.fullScreenOnAwake;
              return this._fullScreenOnAwake;
            }
          }
          return this._fullScreenOnAwake;
        }
        set fullScreenOnAwake(value) {
          if (this._fullScreenOnAwake !== value) {
            this._fullScreenOnAwake = value;
            if (this._impl) {
              this._impl.syncFullScreenOnAwake(value);
            }
          }
        }
        get stayOnBottom() {
          return this._stayOnBottom;
        }
        set stayOnBottom(value) {
          if (this._stayOnBottom !== value) {
            this._stayOnBottom = value;
            if (this._impl) {
              this._impl.syncStayOnBottom(value);
            }
          }
        }
        get nativeVideo() {
          return this._impl && this._impl.video || null;
        }
        get currentTime() {
          if (!this._impl) {
            return this._cachedCurrentTime;
          }
          return this._impl.getCurrentTime();
        }
        set currentTime(val) {
          if (Number.isNaN(val)) {
            warn(`illegal video time! value:${val}`);
            return;
          }
          val = clamp$1(val, 0, this.duration);
          this._cachedCurrentTime = val;
          if (this._impl) {
            this._impl.seekTo(val);
          }
        }
        get duration() {
          if (!this._impl) {
            return 0;
          }
          return this._impl.getDuration();
        }
        get state() {
          if (!this._impl) {
            return "none";
          }
          return this._impl.state;
        }
        get isPlaying() {
          if (!this._impl) {
            return false;
          }
          return this._impl.isPlaying;
        }
        syncSource() {
          if (!this._impl) {
            return;
          }
          if (this._resourceType === ResourceType.REMOTE) {
            this._impl.syncURL(this._remoteURL);
          } else {
            this._impl.syncClip(this._clip);
          }
          this._cachedCurrentTime = 0;
          this._impl.syncLoop(this._loop);
          this._impl.syncVolume(this._volume);
          this._impl.syncMute(this._mute);
          this._impl.seekTo(this._cachedCurrentTime);
          this._impl.syncPlaybackRate(this._playbackRate);
          this._impl.syncStayOnBottom(this._stayOnBottom);
          this._impl.syncKeepAspectRatio(this._keepAspectRatio);
          this._impl.syncFullScreenOnAwake(this._fullScreenOnAwake);
        }
        __preload() {
          this._impl = VideoPlayerImplManager.getImpl(this);
          this.syncSource();
          this._impl.componentEventList.set("meta-loaded", this.onMetaLoaded.bind(this));
          this._impl.componentEventList.set("ready-to-play", this.onReadyToPlay.bind(this));
          this._impl.componentEventList.set("playing", this.onPlaying.bind(this));
          this._impl.componentEventList.set("paused", this.onPaused.bind(this));
          this._impl.componentEventList.set("stopped", this.onStopped.bind(this));
          this._impl.componentEventList.set("completed", this.onCompleted.bind(this));
          this._impl.componentEventList.set("error", this.onError.bind(this));
          this._impl.componentEventList.set("clicked", this.onClicked.bind(this));
          if (this._playOnAwake && this._impl.loaded) {
            this.play();
          }
        }
        onEnable() {
          if (this._impl) {
            this._impl.enable();
          }
        }
        onDisable() {
          if (this._impl) {
            this._impl.disable();
          }
        }
        onDestroy() {
          if (this._impl) {
            this._impl.destroy();
            this._impl = null;
          }
        }
        update(dt) {
          if (this._impl) {
            this._impl.syncMatrix();
          }
        }
        onMetaLoaded() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "meta-loaded");
          this.node.emit('meta-loaded', this);
        }
        onReadyToPlay() {
          if (this._playOnAwake && !this.isPlaying) {
            this.play();
          }
          EventHandler.emitEvents(this.videoPlayerEvent, this, "ready-to-play");
          this.node.emit("ready-to-play", this);
        }
        onPlaying() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "playing");
          this.node.emit("playing", this);
        }
        onPaused() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "paused");
          this.node.emit("paused", this);
        }
        onStopped() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "stopped");
          this.node.emit("stopped", this);
        }
        onCompleted() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "completed");
          this.node.emit("completed", this);
        }
        onError() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "error");
          this.node.emit("error", this);
        }
        onClicked() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, "clicked");
          this.node.emit("clicked", this);
        }
        play() {
          if (this._impl) {
            this._impl.play();
          }
        }
        resume() {
          if (this._impl) {
            this._impl.resume();
          }
        }
        pause() {
          if (this._impl) {
            this._impl.pause();
          }
        }
        stop() {
          if (this._impl) {
            this._impl.stop();
          }
        }
      }, _class3$1.EventType = VideoPlayerEventType, _class3$1.ResourceType = ResourceType, _class3$1), (_initializer$1 = applyDecoratedInitializer(_class2$1.prototype, "_resourceType", [serializable$l], function () {
        return ResourceType.LOCAL;
      }), _initializer2$1 = applyDecoratedInitializer(_class2$1.prototype, "_remoteURL", [serializable$l], function () {
        return '';
      }), _initializer3 = applyDecoratedInitializer(_class2$1.prototype, "_clip", [_dec3$1, serializable$l], function () {
        return null;
      }), _initializer4 = applyDecoratedInitializer(_class2$1.prototype, "_playOnAwake", [serializable$l], function () {
        return true;
      }), _initializer5 = applyDecoratedInitializer(_class2$1.prototype, "_volume", [serializable$l], function () {
        return 1.0;
      }), _initializer6 = applyDecoratedInitializer(_class2$1.prototype, "_mute", [serializable$l], function () {
        return false;
      }), _initializer7 = applyDecoratedInitializer(_class2$1.prototype, "_playbackRate", [serializable$l], function () {
        return 1;
      }), _initializer8 = applyDecoratedInitializer(_class2$1.prototype, "_loop", [serializable$l], function () {
        return false;
      }), _initializer9 = applyDecoratedInitializer(_class2$1.prototype, "_fullScreenOnAwake", [serializable$l], function () {
        return false;
      }), _initializer10 = applyDecoratedInitializer(_class2$1.prototype, "_stayOnBottom", [serializable$l], function () {
        return false;
      }), _initializer11 = applyDecoratedInitializer(_class2$1.prototype, "_keepAspectRatio", [serializable$l], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$1.prototype, "resourceType", [_dec4], Object.getOwnPropertyDescriptor(_class2$1.prototype, "resourceType"), _class2$1.prototype), _applyDecoratedDescriptor(_class2$1.prototype, "clip", [_dec5], Object.getOwnPropertyDescriptor(_class2$1.prototype, "clip"), _class2$1.prototype), _initializer12 = applyDecoratedInitializer(_class2$1.prototype, "videoPlayerEvent", [serializable$l, _dec6], function () {
        return [];
      })), _class2$1)) || _class$1) || _class$1));
      legacyCC.internal.VideoPlayer = VideoPlayer;

      replaceProperty(VideoPlayer.prototype, 'VideoPlayer.prototype', [{
        name: 'onPasued',
        newName: 'onPaused'
      }]);

      class WebViewImpl {
        constructor(component) {
          this._componentEventList = new Map();
          this._state = "none";
          this._wrapper = void 0;
          this._webview = null;
          this._loaded = false;
          this._forceUpdate = false;
          this._component = null;
          this._uiTrans = null;
          this._node = null;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._component = component;
          this._node = component.node;
          this._uiTrans = component.node.getComponent(UITransform);
          this.reset();
          this.createWebView();
        }
        reset() {
          this._wrapper = null;
          this._webview = null;
          this._loaded = false;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._state = "none";
          this._forceUpdate = false;
        }
        get loaded() {
          return this._loaded;
        }
        get componentEventList() {
          return this._componentEventList;
        }
        get webview() {
          return this._webview;
        }
        get state() {
          return this._state;
        }
        get UICamera() {
          return director.root.batcher2D.getFirstRenderCamera(this._node);
        }
        dispatchEvent(key, ...args) {
          const callback = this._componentEventList.get(key);
          if (callback) {
            this._state = key;
            callback.call(this, args);
          }
        }
        destroy() {
          this.removeWebView();
          this._wrapper = null;
          this._webview = null;
          this._loaded = false;
          this._component = null;
          this._uiTrans = null;
          this._forceUpdate = false;
          this._componentEventList.clear();
        }
      }
      legacyCC.internal.WebViewImpl = WebViewImpl;

      const ccdocument = ccwindow$1.document;
      const _mat4_temp = mat4();
      class WebViewImplWeb extends WebViewImpl {
        constructor(component) {
          super(component);
        }
        _bindDomEvent() {
          if (!this.webview) {
            return;
          }
          const onLoaded = e => {
            this._forceUpdate = true;
            this.dispatchEvent("loaded");
            const iframe = e.target;
            const body = iframe.contentDocument && iframe.contentDocument.body;
            if (body && body.innerHTML.includes('404')) {
              this.dispatchEvent("error", body.innerHTML);
            }
          };
          this.webview.addEventListener('load', onLoaded);
        }
        loadURL(url) {
          if (this.webview) {
            this.webview.src = url;
            this.dispatchEvent("loading");
          }
        }
        createWebView() {
          const wrapper = ccdocument.createElement('div');
          this._wrapper = wrapper;
          wrapper.id = 'webview-wrapper';
          wrapper.style['-webkit-overflow'] = 'auto';
          wrapper.style['-webkit-overflow-scrolling'] = 'touch';
          wrapper.style.position = 'absolute';
          wrapper.style.bottom = '0px';
          wrapper.style.left = '0px';
          wrapper.style.transformOrigin = '0px 100% 0px';
          wrapper.style['-webkit-transform-origin'] = '0px 100% 0px';
          game.container.appendChild(wrapper);
          const webview = ccdocument.createElement('iframe');
          this._webview = webview;
          webview.id = 'webview';
          webview.style.border = 'none';
          webview.style.width = '100%';
          webview.style.height = '100%';
          wrapper.appendChild(webview);
          this._bindDomEvent();
        }
        removeWebView() {
          const wrapper = this._wrapper;
          if (contains$1(game.container, wrapper)) {
            game.container.removeChild(wrapper);
          }
          this.reset();
        }
        enable() {
          if (this._wrapper) {
            this._wrapper.style.visibility = 'visible';
          }
        }
        disable() {
          if (this._wrapper) {
            this._wrapper.style.visibility = 'hidden';
          }
        }
        evaluateJS(str) {
          if (this.webview) {
            const win = this.webview.contentWindow;
            if (win) {
              try {
                win.eval(str);
              } catch (e) {
                this.dispatchEvent("error", e);
                error(e);
              }
            }
          }
        }
        setOnJSCallback(callback) {
          warn('The platform does not support');
        }
        setJavascriptInterfaceScheme(scheme) {
          warn('The platform does not support');
        }
        syncMatrix() {
          if (!this._wrapper || !this._uiTrans || !this._component || this._wrapper.style.visibility === 'hidden') return;
          const camera = this.UICamera;
          if (!camera) {
            return;
          }
          this._component.node.getWorldMatrix(_mat4_temp);
          camera.update(true);
          camera.worldMatrixToScreen(_mat4_temp, _mat4_temp, game.canvas.width, game.canvas.height);
          const {
            width,
            height
          } = this._uiTrans.contentSize;
          if (!this._forceUpdate && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
            return;
          }
          this._m00 = _mat4_temp.m00;
          this._m01 = _mat4_temp.m01;
          this._m04 = _mat4_temp.m04;
          this._m05 = _mat4_temp.m05;
          this._m12 = _mat4_temp.m12;
          this._m13 = _mat4_temp.m13;
          this._w = width;
          this._h = height;
          const dpr = screenAdapter.devicePixelRatio;
          const scaleX = 1 / dpr;
          const scaleY = 1 / dpr;
          const container = game.container;
          const sx = _mat4_temp.m00 * scaleX;
          const b = _mat4_temp.m01;
          const c = _mat4_temp.m04;
          const sy = _mat4_temp.m05 * scaleY;
          this._wrapper.style.width = `${width}px`;
          this._wrapper.style.height = `${height}px`;
          const w = this._w * scaleX;
          const h = this._h * scaleY;
          const appx = w * _mat4_temp.m00 * this._uiTrans.anchorX;
          const appy = h * _mat4_temp.m05 * this._uiTrans.anchorY;
          const offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
          const offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
          const tx = _mat4_temp.m12 * scaleX - appx + offsetX;
          const ty = _mat4_temp.m13 * scaleY - appy + offsetY;
          const matrix = `matrix(${sx},${-b},${-c},${sy},${tx},${-ty})`;
          this._wrapper.style.transform = matrix;
          this._wrapper.style['-webkit-transform'] = matrix;
          this._forceUpdate = false;
        }
      }

      class WebViewImplManager {
        static getImpl(component) {
          return new WebViewImplWeb(component);
        }
      }
      legacyCC.internal.WebViewImplManager = WebViewImplManager;

      const WebViewEventType = {
        "NONE": "none",
        "LOADING": "loading",
        "LOADED": "loaded",
        "ERROR": "error"
      };

      var _dec, _dec2, _dec3, _class, _class2, _initializer, _initializer2, _class3;
      let WebView = exports("WebView", (_dec = ccclass$H('cc.WebView'), _dec2 = requireComponent(UITransform), _dec3 = type$a([EventHandler]), _dec(_class = _dec2(_class = (_class2 = (_class3 = class WebView extends Component {
        constructor() {
          super();
          this._url = _initializer && _initializer();
          this._impl = null;
          this.webviewEvents = _initializer2 && _initializer2();
        }
        get url() {
          return this._url;
        }
        set url(val) {
          this._url = val;
          if (this._impl) {
            this._impl.loadURL(val);
          }
        }
        get nativeWebView() {
          return this._impl && this._impl.webview || null;
        }
        get state() {
          if (!this._impl) {
            return "none";
          }
          return this._impl.state;
        }
        setJavascriptInterfaceScheme(scheme) {
          if (this._impl) {
            this._impl.setJavascriptInterfaceScheme(scheme);
          }
        }
        setOnJSCallback(callback) {
          if (this._impl) {
            this._impl.setOnJSCallback(callback);
          }
        }
        evaluateJS(str) {
          if (this._impl) {
            this._impl.evaluateJS(str);
          }
        }
        __preload() {
          this._impl = WebViewImplManager.getImpl(this);
          this._impl.componentEventList.set("loading", this.onLoading.bind(this));
          this._impl.componentEventList.set("loaded", this.onLoaded.bind(this));
          this._impl.componentEventList.set("error", this.onError.bind(this));
          this._impl.loadURL(this._url);
        }
        onLoading() {
          EventHandler.emitEvents(this.webviewEvents, this, "loading");
          this.node.emit("loading", this);
        }
        onLoaded() {
          EventHandler.emitEvents(this.webviewEvents, this, "loaded");
          this.node.emit("loaded", this);
        }
        onError(...args) {
          EventHandler.emitEvents(this.webviewEvents, this, "error", args);
          this.node.emit("error", this, args);
        }
        onEnable() {
          if (this._impl) {
            this._impl.enable();
          }
        }
        onDisable() {
          if (this._impl) {
            this._impl.disable();
          }
        }
        onDestroy() {
          if (this._impl) {
            this._impl.destroy();
            this._impl = null;
          }
        }
        update(dt) {
          if (this._impl) {
            this._impl.syncMatrix();
          }
        }
      }, _class3.EventType = WebViewEventType, _class3), (_initializer = applyDecoratedInitializer(_class2.prototype, "_url", [serializable$l], function () {
        return 'https://cocos.com';
      }), _initializer2 = applyDecoratedInitializer(_class2.prototype, "webviewEvents", [serializable$l, _dec3], function () {
        return [];
      })), _class2)) || _class) || _class));
      legacyCC.internal.WebView = WebView;

    })
  };
}));
